Read the full article at: Loading Scripts with jQuery
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
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!