简体   繁体   中英

Html5 async attribute vs js async property

what is the difference between Html5 async attribute vs js async property.

<script src="http://www.google-analytics.com/ga.js" async>

and

(function() {
    var ga = document.createElement('script'); 
    ga.type = 'text/javascript'; 
    ga.async = true;
    ga.src = 'http://www.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; 
    s.parentNode.insertBefore(ga, s);
})();

are they interchangeable

No, they are not interchangeable.

Script tag with async attribute executes at the first opportunity after it is downloaded and before window.onload event. So you dont know when that script executes. On the other hand, script loaded within a javascript file can execute whenever you want (after or before window.onload event).

Some links: http://davidwalsh.name/html5-async , https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script .

Edit: ga.async = true; as said in Salman A. answer ( https://stackoverflow.com/a/14666847/2044286 ) is omitted by the parser.

The JavaScript is creating the HTML element you are talking about. In JavaScript, the property itself has no meaning, in this case its just a property with the value true .

When the browser reads the HTML, the value gets a meaning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM