As Javascript is becoming more and more in Web apps, many JavaScript codes are not used when pages are loaded for the first time. In this case, to improve the download speed and page rendering efficiency, We need to delay loading of these unused JS files, that is, only download them when they are used. Here, we will first implement the most simple JS inertia loading. In the next few articles, the function will be gradually enhanced until a complete JS/CSS module is loaded to the library. In this series, I will not implement the queue, that is, each JS file is downloaded in parallel, and the callback is executed only after all the JS files are downloaded. Of course, in the second series of JS queue lazyload, each JS file will be loaded sequentially, and each JS file will have a callback opportunity after download. These two methods have their own application scenarios.
First, provide the interface
Lazyload. js (URL // JS file path FN // callback function scope // specifies the callback function execution context after all loads );
Example
Lazyload. js (['a. js', 'B. js', 'C. js'], function () {alert ('Load finished ');});
In firebug, the effect is as follows: Files A, B, and C are downloaded at almost the same time.
This system will do its best to load all JS files, that is, when a file does not exist or fails to be loaded, it will not be interrupted and will still load other JS files. Callback is not performed until all modules are loaded once.
CompleteCode
Lazyload = function (WIN) {var list, isie =/* @ cc_on! @*/! 1, Doc = win.doc ument, head = Doc. getelementsbytagname ('head') [0]; function createel (type, attrs) {var El = Doc. createelement (type), ATTR; For (ATTR in attrs) {el. setattribute (ATTR, attrs [ATTR]);} return El;} function finish (OBJ) {list. shift (); If (! List. length) {obj. FN. call (obj. scope) ;}} function JS (URLs, FN, scope) {list = []. concat (URLs); var OBJ = {scope: Scope | win, FN: fn}; For (VAR I = 0, Len = URLs. length; I <Len; I ++) {var script = createel ('script', {SRC: URLs [I]}); If (isie) {script. onreadystatechange = function () {var readystate = This. readystate; If (readystate = 'loaded' | readystate = 'complete') {This. onreadystatechange = NULL; finish (OBJ) ;}} else {script. onload = script. onerror = function () {finish (OBJ) ;}} head. appendchild (SCRIPT) ;}}return {JS: JS };} (this );
Download example