jQuery .getScript() refactor to prevent caching

Share this article

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

Frequently Asked Questions (FAQs) about jQuery getScript Refactor and Preventing Caching

What is jQuery getScript and how does it work?

jQuery getScript is a powerful AJAX method that loads and executes a JavaScript file using HTTP GET request. It’s a shorthand method for $.ajax(). The getScript method fetches the script from the server and executes it. It’s a convenient way to load scripts on demand, which can help improve the performance of your web pages.

How can I prevent caching with jQuery getScript?

By default, browsers cache scripts to improve performance. However, there are times when you might want to prevent caching, such as during development when you’re making frequent changes to your scripts. To prevent caching with jQuery getScript, you can use the $.ajaxSetup() method to set cache to false before calling getScript.

What are the benefits of refactoring jQuery getScript?

Refactoring jQuery getScript can make your code cleaner, more efficient, and easier to understand. It can also help you identify and eliminate any redundancies or inefficiencies in your code. Refactoring can also make your code more modular, making it easier to test and maintain.

How can I refactor jQuery getScript?

Refactoring jQuery getScript involves breaking down the code into smaller, more manageable functions. This can make the code easier to understand and maintain. You can also use the $.Deferred object to manage callbacks, which can make your code more efficient and easier to debug.

What is the difference between jQuery getScript and other AJAX methods?

jQuery getScript is a shorthand AJAX method specifically designed to load and execute a JavaScript file. Other AJAX methods, such as $.ajax(), $.get(), and $.post(), can be used to send and retrieve data from a server, but they don’t automatically execute the returned script like getScript does.

Can I use jQuery getScript with other JavaScript libraries?

Yes, you can use jQuery getScript with other JavaScript libraries. However, you need to ensure that there are no conflicts between jQuery and the other libraries. You can use the jQuery.noConflict() method to avoid conflicts.

How can I handle errors with jQuery getScript?

You can handle errors with jQuery getScript by using the .fail() method. This method is called when the request fails. You can use it to display an error message or perform some other action when the script fails to load.

Can I use jQuery getScript to load scripts from other domains?

Yes, you can use jQuery getScript to load scripts from other domains. However, due to the same-origin policy, the script must be designed to support cross-domain requests.

How can I improve the performance of jQuery getScript?

You can improve the performance of jQuery getScript by minimizing the number of scripts you load, combining multiple scripts into one, and using a content delivery network (CDN) to serve your scripts. You can also use the cache parameter to control whether scripts are cached.

Can I use jQuery getScript in a loop?

Yes, you can use jQuery getScript in a loop. However, because getScript is asynchronous, the scripts may not load in the order you expect. To ensure scripts load in the correct order, you can use the .done() method to chain your getScript calls.

Sam DeeringSam Deering
View Author

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.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week