What is defer

Can you please tell me what is defer and async attribute

Hi, welcome to the forums.

If you haven’t already completed it, the Asynchronous JavaScript course is a good introduction to the topic.

Broadly, however their usage is as follows.

The defer attribute is used when loading a JavaScript file, and tells the browser that it does not need to wait for this script to load before continuing to load the rest of the page. When the browser parses your HTML, it starts at the top and works down line by line.

As a result, when it gets to a line like <script src="./js/mysupercomplexprogram.js">, it will wait for the entire JS file to load before moving to the next line.

By changing the tag to <script src="./js/mysupercomplexprogram.js" defer> we tell the browser that it needs to load this JavaScript file, but it can do so after it has loaded the rest of the page. The browser will, in effect, come back to this tag and load it later. (Much like how you would go back to a tricky problem on a math test after having done the rest of the questions.)

The async attribute works in a similar way, in that it allows the browser to continue rendering the page without waiting for the JavaScript file to load. async is slightly different to defer, however.

Where defer tells the browser to continue loading the rest of the page, and then come back and load this script, with async the browser will start to load the script in parallel (in the background) whilst continuing to parse the rest of the HTML document. When the JavaScript has loaded, the browser will go back to it at that point and evaluate it.


A real-world analogy could be… making a cake. The overall process of making the cake is the same as the browser parsing your HTML page - there are many steps, which you complete sequentially to get the end result of the cake.

You start making the cake by making the cake batter, put it in the tin, then into the oven… then, whilst it’s in the oven, you go and start making the frosting. You don’t wait for the cake to be baked and cooled before doing this, so you’re still “baking the cake” - the process of “make the frosting” is being done asynchronously while the cake is baking so that you don’t have to wait to eat the cake later.

Once the cake is baked, and has had time to cool, you can come back to it and decorate it. This is when you can add the frosting you made earlier, and any other accoutrements (like sprinkles). Decorating the cake is a deferred action - you’ve gone back to do it after every other part of making the cake is finished.

The overall process of baking the cake is the same as your browser parsing the HTML document,
making the frosting is the async operation, akin to the browser loading a script with that attribute,
and when everything else is done, we go back to the bits we had to defer right at the end.

Hope that helps.