Async and Defer

async and defer

async

  There are actually two ways we can bypass the problem of the blocking script — async and defer.<br/>

  Async scripts will download the script without blocking rendering the page and will execute it as soon as the script finishes downloading.<br/>

  You get no guarantee that scripts will run in any specific order, only that they will not stop the rest of the page from displaying. <br/>

  It is best to use async when the scripts in the page run independently from each other and depend on no other script on the page.<br/>

For example, if you have the following script elements:

<script async src="js/vendor/jquery.js"></script>

<script async src="js/script2.js"></script>

<script async src="js/script3.js"></script>

  You can’t rely on the order the scripts will load in. jquery.js may load before or after script2.js and script3.js and if this is the case, any functions in those scripts depending on jquery will produce an error because jquery will not be defined at the time the script runs.<br/>

defer

  Defer will run the scripts in the order they appear in the page and execute them as soon as the script and content are downloaded:<br/>

<script defer src="js/vendor/jquery.js"></script>

<script defer src="js/script2.js"></script>

<script defer src="js/script3.js"></script>

  All the scripts with the defer attribute will load in the order they appear on the page.<br/>

  So in the second example, we can be sure that jquery.js will load before script2.js and script3.js and that script2.js will load before script3.js.<br/>

To summarize:

  • If your scripts don’t need to wait for parsing and can run independently without dependencies, then use async.<br/>
  • If your scripts need to wait for parsing and depend on other scripts load them using defer and put their corresponding <script> elements in the order you want the browser to execute them.<br/>
    原文作者:Jalever
    原文地址: https://segmentfault.com/a/1190000018477460
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞