jQuery .getScript() refactor to prevent caching
Share
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.
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 });