Home >Web Front-end >JS Tutorial >Delay loading of JavaScript code to improve speed_javascript tips
Delayed loading of js code improves speed. The specific content is as follows:
If there is a large amount of javascript code in the webpage, it will greatly affect the access speed of the webpage. Here is a brief introduction on how to deal with this problem.
1. Delayed loading of js files:
You can use the timer function setTimeout() to delay loading of external js files, for example:
<script type="text/javascript" src="" id="my"></script> <script type="text/javascript"> var js=document.getElementById("my"); function addjs(){ js.src="js/js.js"; } setTimeout(addjs,3000); </script>
The above code can realize that the js code will be loaded after 3 seconds, which can improve the speed to a certain extent.
2. Place the js code behind the web page content:
This is relatively simple. Needless to say, it is to put the js code behind the web page content and one at the bottom of the body. In this way, the content can be loaded first and then the js code is executed, which can also improve the performance to a certain extent. speed.
The following will introduce to you how to delay loading or final loading of JS advertising code to speed up page loading
JS advertising code delays loading or is loaded last to speed up page loading. If there are a lot of JS advertising codes in the page, or other js/' target='_blank' class='u'>JS code is too large, this It will take a lot of time to load. Use JS ad code to delay loading or load last to speed up page loading.
First, JS lazy loading
The code is as follows:
<script language="JavaScript" src="" id="my"></script> <script> setTimeout("document.getElementById('my').src='include/php100.php'; ",3000);//延时3秒 </script>
Second, the JS ad code is loaded last
Insert the following code where you need to insert JS:
Program code
<SPAN id=L4EVER>LOADING...</SPAN>
Of course, that LOADING... you can change it to a small picture you like. It looks very AJAX effective.
Then insert at the bottom of the page:
<SPAN class=spanclass id=AD_L4EVER> 你的JS代码在这里!</SPAN> <script>L4EVER.innerHTML=AD_L4EVER.innerHTML;AD_L4EVER.innerHTML="";</script>
Third, JS is loaded last
Where you want to display the JS ad code
<div id="guangg1"></div>
Advertising content you want to display
<div id="ggad1"><script language="javascript" src="/frontpage/include/php100.js"></script></div>
Determine whether the ad position to be displayed exists
<script> function chkdiv(divid){ var chkid=document.getElementById(divid); if(chkid != null) {return true; } else {return false; } } 最后就是显示JS广告代码了 if (chkdiv('guangg1')) { document.getElementById('guangg1').innerHTML= document.getElementById('ggad1').innerHTML; document.getElementById('ggad1').innerHTML=""; } </script>