Home  >  Article  >  Web Front-end  >  jQuery+deferred implements asynchronous sequential loading of JS files

jQuery+deferred implements asynchronous sequential loading of JS files

php中世界最好的语言
php中世界最好的语言Original
2018-04-23 15:11:251092browse

This time I will bring you jQuery deferred to implement asynchronous sequential loading of JS files. What are the precautions for jQuery deferred to implement asynchronous sequential loading of JS files. The following is a practical case, let's take a look.

I read Ruan Yifeng's article "Detailed explanation of jQuery's deferred object" some time ago, and gained some understanding of the usage of deferred in jQuery. Today I saw an article in the garden: The failed experience of reconstructing the JS front-end framework. (By the way, I miss those dead codes), so I shared a solution I wrote before that uses jQuery's deferred to asynchronously load JS files in order. Corrections are welcome.

If you don’t understand deferred in jQuery yet, I strongly recommend that you read Ruan Yifeng’s detailed explanation of jQuery’s deferred object.
The code to load the JS file is as follows:

/* 
Loading 
JavaScript
 Asynchronously 
loadScript.load(["a.js", "b.js"]); 
*/ 
var loadScript = (function() { 
var loadOne = function (url) { 
var dtd = $.Deferred(); 
var node = 
document
.createElement('script'); 
node.type = "text/javascript"; 
var onload = function(){ 
dtd.resolve(); 
}; 
$(node).load(onload).bind('readystatechange', function(){ 
if (node.readyState == 'loaded'){ 
onload(); 
} 
}); 
document.
getElementsByTagName
('head')[0].appendChild(node); 
node.src = url; 
return dtd.promise(); 
}; 
var load = function(urls) { 
if(!$.isArray(urls)) { 
return load([urls]); 
} 
var ret = []; 
for (var i = 0; i < urls.length; i++) { 
ret[i] = loadOne(urls[i]); 
}; 
return $.when.apply($, ret); 
} 
return { 
load: load 
}; 
})();

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps to implement three-level linkage using jquery xml

Use jquery plug-in ajaxupload for file upload

The above is the detailed content of jQuery+deferred implements asynchronous sequential loading of JS files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:jquery upload form styleNext article:jquery upload form style