How to delay loading

 

js lazy loading and help to improve the loading speed of the page, the following are ways to delay loading of:

1. Method of loading time delay setTimeout

Lazy loading js code to the page loads more time

?
1
2
3
4
5
6
7
8
9
10
<script type= "text/javascript" >
   function A(){
     $.post( "/lord/login" ,{name:username,pwd:password}, function (){
       alert( "Hello" );
     });
   }
   $( function (){
     setTimeout( 'A()' , 1000); //延迟1秒
   })
</script>

2. Let js loaded last

Js e.g. redistributed script file, if placed in the head html, js script is loaded before the page will be loaded into the page, and into the body, it will be run in order to load the page from the fallen JavaScript ~~~ code so we can put js files externally introduced into the bottom of the page, to make the final js introduced to speed up page loading speed

3. The above method will allow you to receive occasional Google page speed test tools "lazy loading javascript" warning. So here's the solution will be recommendations from Google Help page.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
//这些代码应被放置在</body>标签前(接近HTML文件底部)
<script type= "text/javascript" >
   function downloadJSAtOnload() {
     var element = document.createElement( "script" );
     element.src = "defer.js" ;
     document.body.appendChild(element);
   }
   if (window.addEventListener)
     window.addEventListener( "load" , downloadJSAtOnload, false );
   else if (window.attachEvent)
     window.attachEvent( "onload" , downloadJSAtOnload);
   else window.onload = downloadJSAtOnload;
</script>

This code means waiting until the entire document is finished loading, and then load external files "defer.js". 

This code using the steps of: 

1). Copy code above

2) Paste the code (HTML document near the bottom of the front HTML tags)

3) Modify the "defer.js" for your external JS file name

4) Make sure you get the file path is correct. For example: If you enter only "defer.js", then "defer.js" certain files and HTML files in the same folder.

Note: This code will load the specified until the document has finished loading external js file. Therefore, should not need to rely on those pages load properly javascript code goes here. The JavaScript code should be divided into two groups. A set of javascript code is needed immediately because the page is loaded, the other group is the javascript code to operate after the page is loaded (for example, add a click event or something else). These need to wait until the page loads JavaScript code before execution, should be placed in an external file, and then imported.

Guess you like

Origin www.cnblogs.com/superclound/p/11261500.html