What exactly is the benefit of the HTML5 async attribute on script elements?

前端 未结 6 1980
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 00:33

I have some confusion around the new async attribute to the script element in HTML5 that I hope someone can give a clear answer to.

Browsers are capable of Parallel Conn

相关标签:
6条回答
  • setting async attribute to true makes sure that the script is loaded along with the rendering of html in parallel.This is essential because if script is placed at end of body and in html we are using something that depends on javascript code,so it won't be loaded and creates issue defer can be used but defer just pauses execution of script and renders html

    0 讨论(0)
  • 2021-02-07 01:27

    Will work:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>$('body').append('Yey');</script>
    

    Will not work:

    <script async src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>$('body').append('Yey');</script>
    
    0 讨论(0)
  • 2021-02-07 01:27

    Async scripts are executed as soon as the script is loaded, so it doesn't guarantee the order of execution (a script you included at the end may execute before the first script file )

    Defer scripts guarantees the order of execution in which they appear in the page.

    0 讨论(0)
  • 2021-02-07 01:33

    There was a great article from Jake Archibald on html5rocks which addresses this topic.

    0 讨论(0)
  • 2021-02-07 01:35

    The async attribute is just a clearer (no ambiguity very straightforward) and cleaner (it will, or is already, part of the respected HTML5 specification) approach to solve the problem. If your site serves scripts from another domain (or CDN) then the async attribute gives you a little reliability (allow the user to at least read the static content) in that the page won't block while a script from a slow (possibly down) remote host is trying to load.

    0 讨论(0)
  • 2021-02-07 01:36

    According to https://www.html5rocks.com/en/tutorials/speed/script-loading/ if a <script> element is added dynamically it may not be executed until DOMContentLoaded is fired. That is, some user agents (e.g. MSIE 10) will wait until DOM is ready before running dynamically added <script> elements.

    I guess Google wants to get their analytics code running faster on those user agents and as such they need to add async flag to tell the browser (e.g. MSIE 10) that it's okay to start executing the script as soon as possible. HTML5 compatible browsers would execute as if the async true even if it was not defined so the async=true has been added only to improve performance with non-HTML5 browsers.

    0 讨论(0)
提交回复
热议问题