When it comes to JavaScript speed optimization, there is one technique every developers should know and embrace: Defer JavaScript
.
Table Of Contents
The behavior of a website
Imaging having an HTML file import 2 scripts: small.js
and big.js
with difference load times.
<head>
<script src="big.js"></script> <!-- Load time: 500ms -->
<script src="small.js"></script> <!-- Load time: 100ms -->
</head>
<body>
<p>...content...</p>
</body>
During page load, a “white screen” might briefly appear before the full page is visible.
Why bother defer JavaScript
Due to it's nature, the browser will stop rendering the page while loading and executing scripts.
As the result, the page content remains hidden until both small.js
and big.js
are fully downloaded and run.
The "white-screen" is nearly invisible for users with fast internet connections. However, for those like me with slower speeds, it result in a significant delay before the entire page becomes visible.
Luckily, Defer JavaScript
comes to the rescue help us pushing all the script to the bottom of the loading process using defer
and async
.
Async vs Defer
Async
Async will move the download of your script into the background and execute the script as soon as the download is finished.
Each async
script operates independently, they don't wait for each other. Whatever loads first - run first:
<head>
<!-- loads first / runs second -->
<script async src="big.js"></script>
<!-- loads second / runs first -->
<script async src="small.js"></script>
</head>
<body>
<p>...content...</p>
</body>
Defer
Defer will move the download of your script into the background and execute the script as soon as the site finished parsing.
It will also respect the execution order of your scripts.
<head>
<!-- loads first / runs first -->
<script defer src="big.js"></script>
<!-- loads second / runs second -->
<script defer src="small.js"></script>
</head>
<body>
<!-- visible immediately -->
<p>...content...</p>
</body>
Summary
async
and defer
both load JavaScript asynchronously without render blocking but with difference in behavior.
Top comments (0)