Using jquery.load() to replace the content of a div everything works great, however there is a major performance issue. The page loaded into the div contains some external JavaScript files and using HttpWatch I have observed the following:
0 0 GET (Cache) text/javascript <host>/js/file1.js
0 0 GET (Cache) text/javascript <host>/js/file2.js
0 0 GET (Cache) text/javascript <host>/js/file3.js
...
etc.
and a little further below (during the same load()):
571 129862 GET 200 text/javascript <host>/js/file1.js?_=1263399258240
569 26439 GET 200 text/javascript <host>/js/file2.js?_=1263399258365
572 14683 GET 200 text/javascript <host>/js/file3.js?_=1263399258396
...
etc.
The same scripts seem to be loaded again for some reason. Even worse, there appears to be a freeze in the browser just before the files are fetched again.
Can I prevent jQuery from loading the files again? This whole issue is causing around a 5-sec delay to my page. Also, what is the meaning of the _=1263399258240?
jQuery has three different cache options. The default
nullallows caching for all requests except scripts and json requests, whilsttrueandfalseapply to all requests. As far as I can tell, you cannot provide an options argument in theload()method, so you need to change the global jQuery ajax options.I’ve given different ways to do this below.
Example 1:
My first example shows how to do this if you want to revert back to normal settings after the load() request:
Important Note that in doing the above, you need to be careful you’re only sending one request at a time, as storing and switching the “default” each time could lead to race conditions. If you need the above functionality and ability to send parallel requests, you’d be better off writing your own wrapper for the
jQuery.ajax()method so you can pass in thecacheoption on a per-request basis. This would be similar to Andres’ suggested approach below, but with the fixes I suggested to specifycache: trueand to usejQuery.html();rather thaninnerHTML. However, it gets more complicated than that, because internally,jQuery.html();requests scripts using the global option, so you’d also need to override some of the internal functionality deep within function calls thathtml();makes – not something to be done lightheartedly, but certainly possible.Example 2: (recommended for the original question asker)
Now, if you don’t care about restoring defaults, and want cache to be on for all ajax requests, you can simply call
$.ajaxSetup({cache: true});and callload()as you previously did:Example 3:
And if you want the myURL to not be loaded from cache (let’s say its dynamic), but do want to cache the scripts, you’ll need to add a unique-ish/random query to myURL, such as: