JavaScript
Article
By Sam Deering

jQuery .getScript() refactor to prevent caching

By Sam Deering

A feature of the jQuery .getScript() function is that it includes a unique id (timestamp or such) to each ajax script call. This poised a problem for me when I was running a setTimeout to get a script but it was reloading the same script… not good. So I decided to refactor jQuery’s .getScrip() slightly to prevent caching and so it only loads the script once.

The new getScript function

//getScript refactor to prevent caching
(function () {
    $.getScript = function(url, callback, cache)
    {
        $.ajax({
                type: "GET",
                url: url,
                success: callback,
                dataType: "script",
                cache: cache
        });
    };
})();

To prove it works, I tested in the HTTP requests load time and look at the circles you can see the script is now loading the cached version in around 7ms.
getScript caching

--ADVERTISEMENT--

Let’s have a close look at the original .getScript() function and how we can call the new function with the extra parameter.

//normal no cached version
$.getScript('js/script.js', function()
{
    //do something after script loaded
});

How to call the new .getScript() function

Simply just include true at the end if you want it to be cached.

//cache = true
$.getScript('js/script.js', function()
{
    //do something after script loaded
}, true);

OR

// turn on cache
$.ajaxSetup({ cache: true });
$.getScript(url, callback);
// turn cache back off
$.ajaxSetup({ cache: false });
  • ralstonrats

    On current versions of jQuery, this behaviour can be disabled for all ajax requests by:

    $.ajaxSetup({cache: true});

    The remaining problem is that .getScript doesn’t track what’s already on the page – so you either need to do further refactoring to keep a list of what’s loaded or wrap the call to $.getScript() in `if (“undefined”==requiredObject)` (where requiredObject is some javascript entity defined in the script)

Recommended
Sponsors
Get the latest in JavaScript, once a week, for free.