Optimize your code: load code at the right time.
<script src="magic.js">
We have three steps
Loading
Parsing
Executing
Loading
- When the browser sees the script tag it asks your server for the script named
magic.js
. Your server sendsmagic.js
to the browser.
Parsing
- The browser then needs to analyze the code.
Executing
- Once the code has been parsed the browser runs it.
All of this (Loading, Parsing, and Executing) takes time so we aim to solve this problem.
Solving the Problem
We have three levels of goodness (three techniques to optimize website performance by loading JavaScript as late as possible.)
Good
Better
Extreme
Good
Don't let scripts block content as it doesn't make the browser load, parse, and execute scripts before visible content loads.
- We take large scripts out of the head and put them in the body.
Better
When you can load those scripts while visible content is loading and tell the browser it's ok to parse and execute them later.
async
Tells the browser that the script can be executed asynchronously. This means while the scripts being fetched keep parsing in the HTML. Once loads stop everything and execute it.
defer
Not only does the browser keep parsing in the HTML while loading the scripts, but it waits to execute the scripts until after the document's been parsed.
Extreme
We are going to tell the browser to wait to load scripts until the visible content is complete.
window.addEventListener("load", function(){
const script = document.createElement("script");
script.src = "script.js";
document.body.appendChild(script);
});
Compare between defer, async, and normal script
In the end, I hope you have known the Three techniques to optimize website performance by loading JavaScript as late as possible.