Here's a JS code optimization is a little trick, the introduction of external js files dynamically loaded to improve page load speed
-
[Basic optimization]
All required <script> tags are placed in the </ body> before, to ensure the completion page rendering script execution before the page without causing congestion problems, this we know everything.
-
Concomitant JS code, as little as possible use the script tag]
The most common way is with js code into a file, so that the page is only used once <script> </ script> tag to import
-
[JS] no plug load
Script tag to be achieved by increasing the async attribute or attributes defer
<script src="file.js" defer></script>
annotation:
async and defer difference is async load automatically execute the script after completion, defer the need to wait for finished loading the page has finished loading will also execute code
-
[Dynamically created script to load - 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);
}
//usage
loadJS('file.js',function(){
alert(1);
});
-
Google operating results browser, script is created dynamically in the head
-
Library package to suggest that you can run individually.
The realization of the principle, there are many good js library can be used, such as LazyLoad.js , support the introduction of an array, open the browser can be seen in the network is synchronized to load js
-
[XHR Load]
Way using ajax loading
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);
}
}
};
xhr.send(null);
-
【总结】
最好的方式还是使用动态创建script的方式加载,当动态创建script,浏览器会分配一个线程去下载src指向的资源,多个script也是同步下载的