DEV Community

Nitin kalra
Nitin kalra

Posted on • Updated on

What is async and defer and how you can use them to load your web app faster

No one likes a slow website? do they?

But the question is, how do we make our website more optimized, especially when it's dependent on large stylesheets?

Well, this blog post has the answer.

But first, let's understand how things work behind the scene...

While loading a webpage, the browser sends a request for each and every external JavaScript file. If there are 3 external JavaScript files, then the browser will send 3 requests. This impacts the loading time of the webpage.

And for that, in HTML5, we've the "async" and "defer" attributes for the "script" element.

But how do they help us in improving the performance of our website?

The async attribute tells the browser to load the JavaScript file asynchronously. That means, the browser does not have to wait for the file to finish downloading before it continues parsing the HTML.

The defer attribute also tells the browser to load the JavaScript file asynchronously, but there's a difference. With the defer attribute, the browser downloads the file during HTML parsing, but waits to execute it until after the HTML parser has finished.

Both async and defer have the same impact on the loading time of the webpage. So, which one should you use?

If you use the async attribute, then the browser will execute the JavaScript code as soon as it's downloaded. This might be fine if the code is very simple. But if the code is more complex, there's a risk that it might impact the loading of other resources on the page.

While if you use the defer attribute, then the browser will execute the JavaScript code only after the HTML parser has finished. So, if there are other resources that need to be loaded, the browser will finish loading those first before it executes the JavaScript code.

In general, it's best to use the defer attribute. That way, you can be sure that your JavaScript code will not impact the loading of other resources on the page.

Below is the syntax for both:

//Usual script tag
<script       src="myscript.js"></script>

//Script tag which is calling the resources with async
<script async src="myscript.js"></script>

//Script tag which is calling the resources with defer
<script defer src="myscript.js"></script>
Enter fullscreen mode Exit fullscreen mode

So what are you waiting for, fire up the editor and try it all yourself.

Feel free to comment with what you have learnt or any queries that you've.

Top comments (0)