This article mainly introduces how to use jQuery to asynchronously load JavaScript scripts. For more information, see JavaScript loaders, which 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 there may be simpler solutions in some cases.
If you are using jQuery, there is a built-in method that can be used to load the script. This method can be used if you want to delay loading plug-ins or any other types of scripts. The following describes how to use it.
Implementation Method
JQuery has the built-in getScript method to load a script. There are several methods to process the returned results. The most basic usage of jQuery. getScript looks like this:
The Code is as follows:
JQuery. getScript ("/path/to/myscript. js? 6.1.3 ", function (data, status, jqxhr ){
/*
After the script has been loaded and executed, you can do some processing.
*/
});
The getScript method returns a jqXHR object, so you can use the following method:
The Code is as follows:
JQuery. getScript ("/path/to/myscript. js? 6.1.3 ")
. Done (function (){
/* Processing after successful execution */
})
. Fail (function (){
/* Processing upon execution failure */
});
The most common scenario for using jQuery. getScript is to delay loading a plug-in and call it after loading:
The Code is as follows:
JQuery. getScript ("jquery. cookie. js? 6.1.3 ")
. Done (function (){
JQuery. cookie ("cookie_name", "value", {expires: 7 });
});
If you need to do more advanced things, such as loading multiple scripts and different types of files (text files, images, CSS files, etc ), I suggest you switch to a more powerful JavaScript loader. If you only want to delay loading the plug-in, instead of simply loading each page, getScript is perfect!
Cache Problems
Note that when jQuery. getScript is used, the timestamp is automatically added after the Script URL so that the script is not cached. Therefore, you need to set to cache scripts for all requests:
The Code is as follows:
JQuery. ajaxSetup ({
Cache: true
});
If you do not want to overwrite all the caches and your AJAX requests, you 'd better use the jQuery. ajax method and set dataType to script. For example:
The Code is as follows:
JQuery. ajax ({
Url: "jquery. cookie. js? 6.1.3 ",
DataType: "script ",
Cache: true
}). Done (function (){
JQuery. cookie ("cookie_name", "value", {expires: 7 });
});
Pay special attention to the cache when loading scripts!