The following describes a JS code optimization of a small skill, through dynamic loading to introduce JS external files to improve the speed of web page loading

[Basic optimization]

Make sure the page is rendered before the script executes without causing page clogging problems, as everyone knows.

Combine JS code and use script tags as little as possible

The most common way to do this is to write code to a JS file and let the page be imported with tags only once

Loading JS without blocking

This is done by adding the defer attribute or async attribute to the Script tag

Comments:

The difference between async and defer is that the script will be executed automatically after the async loading is complete, while the code will be executed only after the page is also loaded

Create script to load dynamically – recommended

function loadJS( url, callback ){

var script = document.createElement('script'), fn = callback || function(){}; script.type = 'text/javascript'; //IE if(script.readyState){ script.onreadystatechange = function(){ if( script.readyState == 'loaded' || script.readyState == 'complete' ){ script.onreadystatechange = null; fn(); }}; }else{// other browsers script.onload = function(){fn(); }; } script.src = url; document.getElementsByTagName('head')[0].appendChild(script);Copy the code

}

/ / usage

loadJS(‘file.js’,function(){

alert(1);
Copy the code

});

The Script is dynamically created in the head when Google Chrome runs

We suggest that you can package into a class library, introduced separately.

This principle also has many good JS class library can be used, such as LazyLoad. Js, support the introduction of the form of array, open the browser in the network can see that JS is loaded synchronously

【XHR 】

Load using Ajax

Code:

var xhr = new XMLHttpRequest;

xhr.open(‘get’,’file.js’,true);

xhr.onreadystatechange = function(){

if( xhr.readyState == 4 ){ if( xhr.status >=200 && xhr.status < 300 || xhr.status == 304 ){ var script = document.createElement('script'); script.type = 'text/javascript'; script.text = xhr.responseText; document.body.appendChild(script); }}Copy the code

};

xhr.send(null);

8. Conclusion

The best way to load a script is to create it dynamically. When a script is created dynamically, the browser allocates a thread to download the resource pointed to by SRC, and multiple scripts are downloaded simultaneously