JavaScript loaders are very powerful and useful tools in web development. Several popular loaders, such as curljs, LABjs and RequireJS, are widely used. They are powerful, but some situations can have simpler solutions.
If you are using jQuery, there is a built-in method for loading scripts. You can use this method if you want to lazy load plugins or any other type of script. Here's how to use it.
Implementation method
jQuery has a built-in getScript method to load a script, and there are several ways to handle the returned results. The most basic usage of jQuery.getScript looks like this:
jQuery.getScript("/path/to/myscript.js", function(data, status, jqxhr) {
/*
After the script has been loaded and executed, you can do some processing
*/
});
getScript method returns a jqXHR object, so it can be used like this:
jQuery.getScript("/path/to/myscript.js")
.done(function() {
/* Processing after successful execution*/
})
.fail(function() {
/* Processing after failed execution*/
});
The most common scenario for using jQuery.getScript is to lazy load a plugin and call it after loading:
jQuery.getScript("jquery.cookie.js")
.done(function() {
jQuery.cookie("cookie_name", "value", { expires : 7 });
});
If you need to do more advanced things like loading multiple scripts and different types of files (text files, images, CSS files, etc.), I recommend you switch to a more powerful JavaScript loader. getScript is perfect if you just want to load the plugin lazily, rather than simply on every page load!
Caching issues It should be noted that when using jQuery.getScript, a timestamp will be automatically added to the end of the script URL to prevent the script from being cached. Therefore you need to set up the cache script for all requests:
jQuery.ajaxSetup({
cache: true
});
If you don't want to overwrite all the cache with your AJAX request, it's better to use jQuery.ajax method and put dataType Set to script, for example:
jQuery.ajax({
url: "jquery.cookie.js",
dataType: "script",
cache: true
}).done(function() {
jQuery.cookie("cookie_name" , "value", { expires: 7 });
});
You need to pay special attention to caching issues when loading scripts!