Skip to main content

jQuery .getScript() refactor to prevent caching

By Sam Deering



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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)
                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

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);


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

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn the basics fo programming with the web's most popular language - JavaScript

A practical guide to leading radical innovation and growth.

Integromat Tower Ad