DEV Community

Sheng Hsu
Sheng Hsu

Posted on

Async vs Defer in JavaScript

In the world of web development, performance is key. One of the ways to improve the performance of your website is by controlling how your JavaScript files are loaded.

This is where the async and defer attributes come into play. These attributes, when used with the <script> tag, can significantly impact the loading and execution of your JavaScript files.

What does Async do?

The async attribute in JavaScript allows the browser to continue parsing the HTML document while a script is being downloaded.

This means that the script is executed as soon as it is available, even if the HTML is not fully parsed. This can speed up the loading time of your page, but it also means that scripts may be executed out of order if they are loaded at different speeds.

What does Defer do?

On the other hand, the defer attribute tells the browser to continue parsing the HTML document while the script is being downloaded, but to wait until the HTML is fully parsed before executing the script.

This ensures that scripts are executed in the order they appear in the HTML document, which can be important if one script depends on another.

Which is better?

The choice between async and defer depends on the specific needs of your website. If your scripts are independent and do not rely on each other, async can be a good choice because it allows scripts to execute as soon as they are available.

However, if your scripts depend on each other, defer may be a better choice because it ensures that scripts are executed in the correct order.

What happens when you use Async and Defer together?

Technically, you can use both async and defer attributes on the same <script> tag. However, this is not recommended.

The reason is that async and defer have different execution behaviors, and using them together can lead to inconsistent results across different browsers.

According to the HTML specification, if both async and defer are present, the async attribute takes precedence in modern browsers, while older browsers that do not support async will fall back to defer.

This can be useful if you want to use async but also want to provide a fallback for older browsers. However, it's important to use this combination intentionally and understand the potential cross-browser implications.

Conclusion

In conclusion, async and defer are powerful tools for controlling how your JavaScript files are loaded and executed.

They can help improve the performance of your website, but they should be used with care. Always consider the dependencies between your scripts and the potential cross-browser implications before deciding which attribute to use.

Top comments (0)