开发者

Reading the contents of an externally linked file in JavaScript

开发者 https://www.devze.com 2023-01-10 21:31 出处:网络
Is there a way in JavaScript to get the contents of a linked file without making a second GET request? That is, if I have开发者_开发知识库

Is there a way in JavaScript to get the contents of a linked file without making a second GET request? That is, if I have

开发者_开发知识库
<link rel="foo" href="bar.txt">

the browser should automatically download bar.txt. Is there any way to read its contents without getting it again (i.e. via jQuery's $.get or similar)?


Edit

I could use a second GET request and as mentioned in the comments there likely wouldn't be a performance hit, but this question is mainly a thought experiment: it seems like it'd be pretty standard functionality, but more and more things point to this not being possible. Is there a reason why?


If the tag has absolutly no other purpose than being a placeholder for the source, then the objective is to prevent the first get rather then the second ;) By using another attribute you avoid the default behaviour.

<link data-src='file.txt' />

'data-...' is a valid HTML5 attribute you can use right now, though the html will not be valid if an older doctype is declared but will still work.

Next when using jQuery:

$('link[data-src]').each(function(){
    var self = $(this)
    , src = self.attr('data-src');
    $.get(src, function(fileContent){
        // do stuff with fileContent
    })
});

Obviously any element will do rather then the link element when using 'data-...', I use this technique myself to add data in a component based architecture, lazily binding resources and meta information to components without it affecting default behaviours/renditions.

0

精彩评论

暂无评论...
验证码 换一张
取 消