资讯专栏INFORMATION COLUMN

Async and Defer

JackJiang / 2163人阅读

async and defer async

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

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

  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.

  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.

For example, if you have the following script elements:





  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.

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:





  All the scripts with the defer attribute will load in the order they appear on the page.

  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.

To summarize:

If your scripts don"t need to wait for parsing and can run independently without dependencies, then use async.

If your scripts need to wait for parsing and depend on other scripts load them using defer and put their corresponding

阅读需要支付1元查看
<