Understand JavaScript async Vs defer Vs inline: When to Use async, defer or inline?

By | August 11, 2020

A html page can load javascript code with three types:

inline: insert javascript code in a html page

For example:

javascript inline mode in html

async: Use <script async src=”.js”></script> to load js file in html page

For example:

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

defer: Use <script defer src=”.js”></script> to load js file in html page

For example:

<script type='text/javascript' defer='defer' src='https://www.tutorialexample.com/wp-content/plugins/enlighter/cache/EnlighterJS.init.js?ver=27b4a337ea'></script>

How is a html page is displayed by browser?

First, a browser will load some resources and parse html code to display. A html page usually will be parsed when resources are loaded. JavaScript inline, async and defer will affect the loaded style of js files in a html page.

The difference among javascript inline, async and defer

As to javascript inline

JavaScript code is inserted in a html page. When a html page is read, browser will render this page after all javascript code is loaded and executed.

For example:

the process of javascript inline in html page

As to javascript async

All javascript files are loaded asynchronously. Browser will aso can load and render html when javascript files are loading.

However, once a js file is loaded, it will start to run immediately. Browser will pause to render html when js file is run.

javascript async mode effect

You should notice:

async mode is only for independent javascript file. jquery.js can not use async mode to load, because many other js files depend on it.

As to javascript defer

JavaScript defer mode allows browser to render a html page when js files are being downloaded. However, all javascript files can be run after the whole html page is parsed.

javascript defer mode effect

When to use javascript inline, async and defer?

If javascript code is very small, you can use inline mode.

If javascrpt code is a file and it is independent, no other js code depends on it, async is a good choice. Otherwise, you should use javascript defer mode.

Leave a Reply