Home > Web Front-end > JS Tutorial > The async attribute of script loads scripts in non-blocking mode_javascript tips

The async attribute of script loads scripts in non-blocking mode_javascript tips

WBOY
Release: 2016-05-16 17:43:34
Original
1409 people have browsed it

1. HTML5 implements the async attribute of script . This new attribute allows js to be loaded in a non-blocking mode in the browser. In addition, script also has a defer attribute. This attribute is currently used by all browsers. All browsers have implemented it (except for early versions of Firefox and Chrome), and IE has done a good job in supporting these properties from the beginning.

Copy code The code is as follows:

//async


//defer


2. The difference between async and defer :
Scripts with async or defer will be downloaded immediately and will not block page parsing, and both provide an optional onload event processing, in the script Called after the download is completed to do some initialization work related to this script. The difference is that async is executed as soon as the download is completed (before the window.onload event) and does not ensure the order of execution, while defer ensures that js is executed in the order it is in the page (before the DOMContentLoaded event).
3. In order to solve browser compatibility issues, you can use the following code
Copy code The code is as follows:

function lazyload() {
var elem = document.createElement("script");
elem.type = "text/javascript";
elem. async = true;
elem.src = "js/dquery.js?v=11"; //Corresponding JS file
document.body.appendChild(elem);
}

if (window.addEventListener) {
window.addEventListener("load", lazyload, false);
} else if (window.attachEvent) {
window.attachEvent("onload", lazyload);
} else {
window.onload = lazyload;}

Since it is asynchronous loading, the corresponding js content needs to be used in the window.onload event. Writing it directly in the page will Report script errors, such as:
The async attribute of script loads scripts in non-blocking mode_javascript tips
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