JavaScript loaders 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 usingJQueryThere is a built-in method that can be used to load scripts. 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:
JQuery. getScript ("/path/to/myscript. js ", 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:
JQuery. getScript ("/path/to/myscript. js "). done (function () {/* processing after successful execution */}). fail (function () {/* processing after execution failure */});
The most common scenario for using jQuery. getScript is to delay loading a plug-in and call it after loading:
jQuery.getScript("jquery.cookie.js").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 functionJavaScriptLoader. 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:
jQuery.ajaxSetup({ cache: true});
If you do not want to overwrite all the caches with yourAJAXRequest, it is best to use the jQuery. ajax method and set dataType to script, for example:
jQuery.ajax({ url: "jquery.cookie.js", dataType: "script", cache: true}).done(function() {jQuery.cookie("cookie_name", "value", { expires: 7 });});
Pay special attention to the cache when loading scripts!
Articles you may be interested in
- 10 popular Metro UI Bootstrap themes and templates
- Select 12 excellent jQuery Ajax paging plug-ins and tutorials
- 10 popular topic Bootstrap in Metro UI Style
- 8 exquisite jQuery plug-ins for loading animations and progress bars
- 35 exquisite CSS3 and HTML5 webpage templates are recommended
English link: Loading Scripts with jQuery via David Walsh
Source: Dream sky ◆ focus on front-end development technology ◆ share web design resources
This article from [dream sky (http://www.cnblogs.com/lhb25 )]