When a script is loaded, it loads in blocking or synchronous mode, which means that the browser waits for the script to finish loading before executing any code after it.
So in this case, script2.js
cannot start loading before script1.js
finishes loading -
<body>
<script src="script1.js"> </script>
<script src="script2.js"> </script>
</body>
As you can imagine, this becomes problematic when -
-
script2
needs variables that are inscript1
-
script1
is really huge, and the entire page needs to wait for the script to finish loading.
The browser waits for the script to finish because it assumes that the script may have code that may update the page contents using document.write
. If your script isn't using document.write
, then waiting for the browser to finish loading isn't useful.
In order to get past this, there are two attributes that can be used - defer
and async
.
-
defer
: defer tells browser that script wont generate any document content and can safely be downloaded without blocking the page and this script should be deferred until all the page is downloaded. defer is executed only when the page is completely parsed. -
async
:async
is similar to defer in the sense that it won't change anything in the DOM, but unlike defer, async scripts are executed as soon as they are downloaded. This is advantageous because scripts can potentially execute sooner.
Syntax -
<script defer src="script1.js"> </script>
<script async src="script2.js"> </script>
TL;DR
Blocking scripts can slow down page. Use defer
or async
to limit effects of blocking script. defer
and async
scripts must not modify page content using document.write
.
-
defer
: defer is executed only when the page is completely parsed. -
async
: async scripts are executed as soon as they are downloaded
Shruti Kapoor
View all recent blogs
Follow on twitter
Top comments (2)
DEV makes use of these techniques to great success.
🎉💯