Dynamically loading JavaScript is a powerful and useful technique. This topic has been discussed on the Internet a lot, and I often use REQUIREJS and dojo to load JS
on some personal projects.
They are powerful, but sometimes they do not outweigh the gains. If you're using jquery, there's a built-in way to load a single JS file. You can use this method when you need to delay loading some JS plug-ins or other types of files. Here is a description of how to use it! jquery Getscript () method loading JavaScript jquery built-in a way 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: The code is 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 like this: code as follows: Jquery.getscript ("/path/to/myscript.js") .done ( function () { * * Yes, no problem, here's what you can do./ }) .fail (function () { /* rely on, immediately execute the salvage operation/}); The most common place to use jquery.getscript is to delay loading a JS plug-in and execute it when the load is complete: Copy code code as follows: Jquery.getscript (" Jquery.cookie.js ") .done (function () { Jquery.cookie (" Cookie_name "," value ", {expires:7});}); II. Caching issues There is a very important problem, when using jquery.getscript, you need to use a timestamp string to follow 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 this: copy Code as follows: Jquery.ajaxsetup ({ CAChe:true}); Code as follows: Jquery.ajax { URL: "Jquery.cookie.js", DataType: "Scri PT ", cache:true}). Done (function () { Jquery.cookie (" Cookie_name "," value ", {expires:7});} ); Be sure to cache the problem when loading the script!