mind set
mind set

Reputation: 133

What's the difference between document.ready and async?

Script in async is loaded after the page loads and (document).ready execute the script on DOM ready, but what is the difference? And which one makes the page loads faster?

<script>   
  $(document).ready(function(){
    //some code
  }); 
</script>

VS

<script async>   
    //some code
</script>

Upvotes: 1

Views: 399

Answers (2)

NoBugs
NoBugs

Reputation: 9496

According to MDN, async has no effect for inline script tag, so the fact that worked probably means the script happens to be at the bottom of the html.

document.ready is a deprecated way jQuery lets you make a DOMContentLoaded listener, and it is better to do jQuery(function($) {...} and include code in that.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370809

For

<script async>   
    //some code
</script>

the async attribute will be ignored, because async is only meaningful when a <script> has a src attribute:

This attribute must not be used if the src attribute is absent (i.e. for inline scripts). If it is included in this case it will have no effect.

So, the <script async> in your question will block HTML parsing once the tag is encountered - it won't operate asynchronously at all.

If the script tag did have a src, then the async tag will download the script asynchronously (HTML parsing is not blocked), and then execute the script as soon as the script has been downloaded (whether or not the page has finished loading first). See here

$(document).ready(function(){ requires the DOMContentLoaded event to fire before the containing function runs, and DOMContentLoaded will run only once the HTML has been completely parsed (though not necessarily before all resources have been downloaded, like images and such).

So, the async script with a src tag may execute sooner than $(document).ready(function(){.

Do note that there's a defer tag, which is nearly the same as $(document).ready(function(){ - a script with a defer tag (and a src) will run just before the DOMContentLoaded event fires.

Upvotes: 3

Related Questions