Home > Article > Web Front-end > Use the async attribute to asynchronously load and execute JavaScript methods
One of the biggest reasons why I am excited about HTML5 is that the new functions and features implemented in it are all that we have been looking forward to for a long time. For example, I've been using placeholders before, but I had to implement them in JavaScript. The async
attribute provided for JavaScript tags in HTML5 enables JavaScript to be loaded and executed asynchronously. Previously I needed various JavaScript plugins to achieve this functionality, but now this new attribute allows us to easily implement asynchronous loading.
It’s really simple, just like this:
<script async src="siteScript.js" onload="myInit()"></script>
In fact, if you are a rigorous programmer, you should More than 90% of SCRIPT
tags use the async
attribute.
There is also a defer
attribute similar to the async
attribute:
<script defer src="siteScript.js" onload="myInit()"></script>
and The syntax of the async
attribute is very similar.
This WebKit blog explains the differences between
defer and
async very clearly:
The browser will immediately load and parse scripts marked with the
async
attribute or thedefer
attribute, and will also support initialization that relies on this script. onload event. The difference between theasync
attribute and thedefer
attribute is when the script is executed. Scripts marked with theasync
attribute will be executed after the download is completed, without waiting for the window's load event. This means that scripts marked with theasync
attribute will not necessarily be executed in the order they are embedded in the page. Scripts marked with thedefer
attribute will be executed in the order they appear on the page. Execution will start after parsing is completely completed, but before the document'sDOMContentLoaded
event.
Quote from the Safari blog:
WebKit engine browsers (Google Chrome and Safari). Firefox supports the async and defer attributes starting with version 3.6. IE has also supported the defer attribute for a long time, but does not support the async attribute. The onload attribute is supported in IE9.
It makes me very happy to see various browsers implement the async
function. It is indeed a big problem to be stuck by JavaScript when browsing the website page. The asynchronous loading and execution capabilities of the async
attribute will definitely increase the page speed of the website.
Recommended tutorial: "javascript basic tutorial"
The above is the detailed content of Use the async attribute to asynchronously load and execute JavaScript methods. For more information, please follow other related articles on the PHP Chinese website!