Dynamic Loading of Javascript is a very powerful and useful technology. I have discussed many topics on the Internet. I often use RequireJS and Dojo to load js in some personal projects. They are very powerful, but sometimes they will not be worth the candle. If you are using jQuery, there is a built-in method in it that can be used to load a single js file. This method can be used when you need to delay loading some js plug-ins or other types of files. The following describes how to use it!
I. jQuery getScript () method loading JavaScript
JQuery has a built-in method to load a single js file. After loading is complete, you can perform subsequent operations in the callback function. The most basic method to use jQuery. getScript is as follows:
The Code is as follows:
JQuery. getScript ("/path/to/myscript. js? 6.1.3 ", function (data, status, jqxhr ){
/*
Do some things that need to be executed after loading.
*/
});
This getScript method returns a jqxhr, which you can use as follows:
The Code is as follows:
JQuery. getScript ("/path/to/myscript. js? 6.1.3 ")
. Done (function (){
/* Yes. No problem. What can I do here */
})
. Fail (function (){
/* Rely on and immediately perform the rescue operation */
});
The most common use of jQuery. getScript is to delay loading a js plug-in and execute it when loading is complete:
The Code is as follows:
JQuery. getScript ("jquery. cookie. js? 6.1.3 ")
. Done (function (){
JQuery. cookie ("cookie_name", "value", {expires: 7 });
});
Ii. cache Problems
There is a very important issue. When using jQuery. getScript, you need to use a timestamp string behind the js address to be loaded to prevent it from being cached. However, if you want this script to be cached, you need to set the global cache variable, as shown below:
The Code is as follows:
JQuery. ajaxSetup ({
Cache: true
});
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 });
});
Be careful when loading scripts!