views:

45

answers:

1

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?

+1  A: 

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.

BGerrissen
Interesting approach! I'm interested in seeing if JavaScript can piggy-back off of files that would've already been loaded anyway, though.
Mark Trapp
Due to security issues, javascript is not able to read already loaded files, since that would require disc access (tmp internet files) and browsers are generally pretty firm about denying access to files on disc. There's also no API for files loaded inside a page context through means other then XMLHTTPRequests. This is exactly why Ajax has been such a succesful and popular technique, because there are no alternatives ;) Well, you could embed the contents of the file inside the HTML rather then linking to it and quering for it when you need to.
BGerrissen
Awesome, thanks for the explanation. Your comment should be part of your answer!
Mark Trapp