Dynamically loading JavaScript is a very powerful and useful technique. This topic has been discussed in this site a lot, I also often on some personal projects using REQUIREJS and dojo to load JS. They are powerful, but sometimes they are not worth the candle. If you are using jquery, there is a built-in method that can be used to load a single JS file. You can use this method when you need to delay loading some JS plugins or other types of files. Here's how to use it! JQuery JavaScript
jquery has a built-in method to load a single JS file, and you can perform subsequent operations in the callback function when the load is complete. The most basic way to use jQuery.getScript this is:
Jquery.getscript ("/path/to/myscript.js", function (data, status, JQXHR) {/* do something that needs to be done after the load is completed */});
This getScript method returns a JQXHR, and you can use it as follows:
Jquery.getscript ("/path/to/myscript.js"). Done (function () {/* Yes, no problem, what can I do here */}). Fail (function () {/*/, Save now */} );
The most common place to use jQuery.getScript is to delay loading a JS plugin and execute it when the load is complete:
Jquery.getscript ("Jquery.cookie.js"). Done (function () {Jquery.cookie ("Cookie_name", "value", {expires:7});});
If you need more advanced features, such as loading multiple scripts, or loading different types of files (text files, images, CSS, etc.), I suggest you use a dedicated JavaScript loading tool. If it is to delay loading a JS plugin, to avoid each page to load, this getScript is perfect.
Caching issues
There is a very important problem when using jQuery.getScript , you need to use a timestamp string followed by the need to load the JS address, to prevent it from being cached. However, if you want this script to be cached, you need to set the global cache variable, like this:
Jquery.ajaxsetup ({ cache:true});
If you do not want to use the global cache variable, you can also use it jQuery.ajax , and note dataType that it is script :
Jquery.ajax ({ URL: "Jquery.cookie.js", dataType: "Script", cache:true}). Done (function () { Jquery.cookie ("Cookie_name", "value", {expires:7});
Be sure to cache the problem when loading scripts!
Reprinted from Http://www.webhek.com/loading-scripts-jquery?_biz=MjM5OTA1MDUyMA==&mid=407358558&idx=2&sn= B21877f23bf4063fa311185009c1f0b7&scene=0#wechat_redirect1465174046140?ref=myread
Use jquery to load JS scripts