Home > Web Front-end > JS Tutorial > body text

Asynchronous loading of js files in html pages

韦小宝
Release: 2018-03-14 18:29:34
Original
1804 people have browsed it

Generally, third-party js is introduced directly. If the third-party is slow, it will block the rendering of the page. When the user is waiting, he will see a blank space. This user experience is not very good. Therefore, some js that do not need to be run immediately can be loaded asynchronously.

There are two loading methods, as follows

Add async=”async” in the script

async is a new attribute of html5, low version browsing The server is not compatible

<script type="text/javascript" async="async" src="http://thirdpart/js.js" ></script>
Copy after login

Use js method to load asynchronously

This method is to add script to the page after the listening page is loaded, so as to introduce the js file

(function() {
function asyncLoad() {
var src = "http://thirdpart/js.js";
var urls = src.split(",");
var x = document.getElementsByTagName(&#39;body&#39;);
if(x && x[0]){
for (var i = 0; i < urls.length; i++) {
var s = document.createElement(&#39;script&#39;);
s.type = &#39;text/javascript&#39;;
s.async = true;
s.src = urls[i];
x[0].appendChild(s);
}
}
}
window.attachEvent ? window.attachEvent(&#39;onload&#39;, asyncLoad) :
window.addEventListener(&#39;load&#39;, asyncLoad, false);
})();
Copy after login

The above is the detailed content of Asynchronous loading of js files in html pages. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template