Async vs Defer, which is better to load a script?

Loading the web page fast is so critical right now because of the various impact that it creates. SEO, UX, User Satisfaction are the various things that are affected.

So we want our web page to load as fast as possible or at least want the first paint to happen as soon as possible.

In the current web development, we cannot think of building a web app that does not contain javascript. It is a must and we should always think to handle its loading/execution carefully for better performance.

Because -

JavaScript is considered a "parser blocking resource". This means that the parsing of the HTML document itself is blocked by JavaScript.

Loading script in the head

As a beginner, we have been taught to import or load our external script in the head HTML element.

The HTML parsing starts from the top and moves to the bottom. Whenever it hits the script tag it stops the parsing of the DOM and starts fetching the script (If it is external) and then executes it and later resumes the parsing of DOM.

Script

Now if script takes longer to load and execute if the network connection is slow or you are on a mobile device then the user will see a blank page which is not we want.

Loading script at the end of the body

To fix this, it is advised to place our script tags at the bottom of the body tag to load it at the end.

This will render the DOM and then load the script which gives us much better user experience.

But it is still not a perfect solution because for long HTML documents there can be noticeable delays.

This is how we used to fix the issues earlier in older browsers. But now with HTML5 we have two extra attributes for script tag, async and defer.