In this article, we’re going to look at how we can use
defer to control the execution order of our scripts & optimize our page load speed!
Today, all modern browsers support the
defer attributes on scripts. These attributes tell the browser it's safe to continue loading the page, while the scripts are being downloaded.
Let’s start by defining how
<script> works without any attributes applied. The HTML file will load (aka be “parsed”) until the script file is found. At that point, parsing will stop and a request will be made to fetch the file (if it’s located externally). The script will then be executed before parsing is resumed.
By adding the
async attribute, the browser will download the file during HTML parsing and it will pause the HTML parser to execute it when it has finished downloading.
<script src="directory/script1.js" async></script> <script src="directory/script2.js" async></script>
Essentially, scripts with the async attribute are executed asynchronously. Meaning the script is executed as soon as it’s downloaded, without blocking the browser.
It’s also possible that (in the above example) script 2 could download and execute before script 1.
defer attribute is added, the browser downloads the file during HTML parsing and will only execute it after the parser has completed.
defer scripts are guaranteed to execute in the order that they appear in the document (i.e. first script 1, then script 2). This also does not block the browser.
<script src="directory/script1.js" defer></script> <script src="directory/script2.js" defer></script>
Unlike async scripts, defer scripts are only executed after the entire document has been loaded.
So when should I use each method?
Typically you’ll want to use
async whenever possible, followed by
defer in certain circumstances. Here are some general rules to follow:
- If the script is modular and does not rely on any scripts then use
- If the script relies upon or is relied upon by another script then use
- If the script is small and is relied upon by an
asyncscript then use an inline
scriptwith no attributes placed above the
When it comes to the actual script placement within your document. The current state-of-the-art is to put scripts in the
<head> tag and use the
defer attributes. This allows your scripts to be downloaded ASAP without blocking your browser!
A little about me..
Hey, I’m Tim! 👋
I’m a developer, tech writer & author. If you’d like to see all of my articles, you're in the right place! Browse the blog categories to find what interests you.
I’m currently working on building my Complete Guide to Freelancing. The bad news is that it’s not available yet! But if it’s something you might be interested in, you can sign up to be notified when it’s available 👍
Thanks for reading!