Home >Web Front-end >JS Tutorial >JavaScript dynamic loading three_javascript skills

JavaScript dynamic loading three_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:50:271102browse

The previous two articles introduced how to implement it step by step by dynamically loading JS files or JS modules.

First, the separation between module loading and callback functions is achieved through synchronous strategy, and then the separation between module loading and callback functions is achieved through asynchronous strategy.

This article is mainly to talk about how to optimize the asynchronous strategy and realize random loading (not loading modules in any order). The file is loaded after the page is Ready. Let’s take up the questions left over from the previous article

1. Load the page after it is ready

2. Add modules at will to load

Look at the first question, this question In fact, it is relatively simple. It mainly listens to the DOMContentLoaded event of the page. I won’t explain it here. I searched on the Internet and found a bunch of answers, so I went directly to the code.

Copy code The code is as follows:

Using.ready = function(callback){
readyList.push(callback);

if(document.addEventListener){
document.addEventListener("DOMContentLoaded",_ready,false);
return;
}
// for IE
var domReady = function(){
try{
document.documentElement.doScroll("left");
_ready();
}catch(ex){
setTimeout(domReady,1);
return;
}
}
domReady();
}

The most difficult thing to understand in this piece of code is probably
Copy code The code is as follows:

document.documentElement.doScroll("left");

This is actually the page loading completion event of IE. Simply put, after the label in IE is loaded, Scroll can be operated. Then use this principle to determine whether the page in IE has been loaded.

There is a _ready function in it. This function is used to perform all loading functions after the page is loaded. Paste the code

(Edit this paragraph: The Ready function after the page is loaded is not the window.load of native JS that we think of. Simply put, it is just the loading of the DOM structure in the page. For specific information, you can Google it on Baidu)
Copy code The code is as follows:

var readyList = [];
var _ready = function(){
while(readyList.length > 0){
var func = readyList.shift();
func();
}
document. removeEventListener("DOMContentLoaded",_ready,false);
}

The following is the focus of this blog post. Let’s take a look at the code first
Copy the code The code is as follows:

Using.asyn = function(callback ){
asynQueue.push(callback);
if(!_execAsyn.isRunning){
_execAsyn();
}
}

Still notify Using The required modules are loaded, but an asynQueue array and _execAsyn function are added to it. Their functions are respectively

asynQueue is used to save the functions to be called back after asynchronous loading. There is nothing to explain. It is an array, which can be understood as creating a queue of functions.

_execAsyn is used to execute the saved callback functions, that is, execute the saved functions one by one. Take a look at the code. The function of each line in the code is commented
Copy the code The code is as follows:

var _execAsyn = function(){
// Create a variable to cache the function that needs to be executed
var func = null;
// If there are unexecuted functions in the queue, execute the operation
if(asynQueue.length > 0){
// Modify the _execAsyn function to the running state
_execAsyn.isRunning = true;
// Get the first function in the queue that needs to be executed
func = asynQueue.shift();
// Call the asynchronous loading module Using.fn.script function and pass in the callback function that needs to be executed after loading is complete
Using.fn.script(function(){
// The current function that needs to be executed
func();
// Iterate _execAsyn until there is no function that needs to be executed in the queue
_execAsyn();
});
/ / If there is no function that needs to be executed in the queue
}else{
// Change the _execAsyn running status to false
_execAsyn.isRunning = false;
}
}

이 함수는 특별히 설명할 것은 없지만, 간단히 말해서 실행해야 할 함수를 하나씩 실행하는 것 뿐입니다. 그러면 주목해야 할 것은 왜 큐를 연산할 때 루프를 사용하지 않고 반복(iteration)을 사용하는지이다. 그 이유는

1. 큐에 언제든지 실행해야 할 새로운 함수가 있을 수 있기 때문이다. 루프를 사용하면 항상 마지막에 함수가 삽입되기 때문에 최신 함수가 실행되지 않을 수 있다. 대기열

2 .Using.fn.script는 비동기식입니다. 루프인 경우 현재 함수가 아직 실행되지 않았으며 다음 함수가 실행 상태에 진입했을 수 있습니다. 그러면 그 자체로 여러 기능을 동시에 실행하는 속도가 더 높아질 수 있습니다. 여기서 왜 여러 기능의 병렬성을 제한해야 합니까? 그 이유도 매우 간단합니다. 왜냐하면 대기열에 있는 함수가 실행될 때마다 해당 모듈을 로드해야 하기 때문입니다. 따라서 동일한 모듈에 의존하는 두 개 이상의 함수를 실행하고 병렬로 실행해야 하는 경우 동일한 모듈이 여러 번 로드될 수 있으며 이로 인해 후속 기능이 실행되지 않고 예외가 발생할 수 있습니다.

UsingJS 전체의 핵심 부분입니다. 여기에는 JavaScript 동적 로딩 기사의 마지막 부분에 언급된 Using.Class.create 함수를 추가했습니다.

마지막으로 페이지 사용법을 살펴보세요:
코드 복사 코드는 다음과 같습니다