Loading Scripts with jQuery
JavaScript loaders are incredibly powerful and useful utilities. I've even covered a few of them on this blog, like curljs and LABjs, and have used RequireJS and the Dojo loader on personal projects. They're super powerful but can be overkill in some cases. If you're using jQuery, there's a built in method for loading a single script which may come in handy if you'd like to lazy load a plugin or any other type of script. Here's how to use it!
The jQuery JavaScript
jQuery is fitted with a getScript method to load one script; handling the result can be done in a few ways. A basic usage of jQuery.getScript
would look like:
jQuery.getScript("/path/to/myscript.js", function(data, status, jqxhr) { /* do something now that the script is loaded and code has been executed */ });
The getScript
method returns a jqxhr so you can also use it as a follows:
jQuery.getScript("/path/to/myscript.js") .done(function() { /* yay, all good, do something */ }) .fail(function() { /* boo, fall back to something else */ });
The obvious use case for jQuery.getScript
is lazy loading of a plugin and using it once loaded:
jQuery.getScript("jquery.cookie.js") .done(function() { jQuery.cookie("cookie_name", "value", { expires: 7 }); });
If you need to do more advanced stuff like loading multiple scripts and different types of file types (text files, images, css files, etc), I'd recommend you switched to a JavaScript loader. In the case of wanting to lazy load a plugin and not simply load it with each page, getScript
is perfect!
Update: Caching
It's important to note that when using jQuery.getScript
, a timestamp is added to the script URL so the script ends up not being cached. Unfortunately you need to override all caching to cache the script and still use jQuery.getScript
:
jQuery.ajaxSetup({ cache: true });
If you don't want to override all caching with your AJAX requests, it's best the use the jQuery.ajax
method with a dataType
of script
:
jQuery.ajax({ url: "jquery.cookie.js", dataType: "script", cache: true }).done(function() { jQuery.cookie("cookie_name", "value", { expires: 7 }); });
Keep caching in mind when loading your scripts!
Nice! Makes me want to dig through all the available jQuery methods again.
Just remember
getScript
appends a random value on the GET request to prevent caching. If you actually want to allow caching of the script you have to roll your own$.ajax
method.Excellent post!
However, be aware that the default behavior of getScript is to load the content using AJAX and insert it in an inline script-tag on the website. Because the browser has no way to tell where the content actually came from, the dev tool (built-in, Firebug etc.) cannot give ANY helpful information at all (most likely it will refer to a non-existing line in the jQuery file) if there is any error in the loaded JavaScript file.
To avoid this behavior, one can instead use
$.ajax
and setcrossDomain: true
in the parameter object. This forces jQuery to instead create a script-tag with the src-attribute set to the url of the script and debugging will again work as expected.Nice post as always! Will use this in my future projects for sure!
Wrote an extension to the getScript method that allows for multiple scripts to be loaded synchronously and asynchronously. Hope it helps!
https://github.com/hudsonfoo/jquery-getscripts
Is it possible to use getScript to load JS file when a select box is clicked?
I found a plugin with ~50 translations (eternicode datepicker). Since my app has a “choose language” select box, it would be nice if I could load the file(s) when requested by user. If it is possible, an example would be helpful for the noobs like me. :)
What about loading 3rd party scripts and setting a timeout?
Lets say I do not want a 3rd party script to hold up the loading of my site, is it possible to have a timeout with this so that – lets say, after 5 seconds, if it hasn’t loaded I can abort the
getScript
call?James, would this work?
> do something now that the script is loaded and code has been executed
This is not true. The script is loaded at that point but not necessarily executed. Check the API docs.
Pieter Pol is right. The API docs and personal experience say so.
Hi,
Nice post, I have a question here. Is it possible to add and get multiple JS files using getScript(), Thanks in advance.
Note that you can also set
cache:true
for the specific getScript request if you use the options object signature: