Search code examples
javascriptjquerygetscript

Jquery getScript caching


By Default $.getScript() disables caching and you can use $.ajaxSetup and set caching to true. When testing if the script is actually cached with Firebug most of the time the script is coming back at 200 (Which means the script is a fresh copy) and one in maybe 20 or 30 times it will come back 304 (meaning it used a cached version). Why is it getting a new copy the vast majority of the time?

$.ajaxSetup({
    cache: true
 });

 $.getScript( scriptFile );

The files that getScript retrieves have not been edited and the requests are a page change apart.


Solution

  • There is an error as of the date this question was posted where both Firefox and Chrome would state that a script is not being loaded from Cache when it indeed is. As of the date of this answer this issue still exists. The easiest way to test is to use console.log and send out a version number.

    To cache a dynamically loaded script it it simply done by using the following code.

    function onDemandScript ( url, callback ) {
        callback = (typeof callback != 'undefined') ? callback : {};
    
        $.ajax({
             type: "GET",
             url: url,
             success: callback,
             dataType: "script",
             cache: true
         });    
    }
    

    For development you should comment out cache: true.