Dynamically loading JavaScript is a very powerful and useful technique. This topic has been discussed on the Internet a lot, I also often on some personal projects using Requirejs and dojo loading 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 GetScript () method load Javascript jquery built-in a method to load a single JS file, you can perform subsequent operations in the callback function when the load is complete. The most basic way to use Jquery.getscript is this: code as follows: Jquery.getscript ("/path/to/myscript.js", function (data, status, JQXHR) { /* do some things that need to be done after loading */ }); This getscript method returns a JQXHR, you can use it as follows: The code is as follows: Jquery.getscript ("/path/to/myscript.js") .done (function () { /* Yes, no problem, what can I do here */ }) .fail (function () { /* On, immediate rescue operation */}); the most common place to use jquery.getscript is to delay loading a JS plugin and execute it when the load is complete: The copy code code is as follows: Jquery.getscript ("Jquery.cookie.js") .done (function () { Jquery.cookie ("Cookie_ Name "," value ", {expires:7});}); two, cache problem There is a very important problem, when using jquery.getscript, you need to use a timestamp string followed by the JS address that needs 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, like so: copy code code as follows: Jquery.ajaxsetup ({ cache:true}); The code is as follows: 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!
How to dynamically load JS script files using jquery