- Speed up your website with async and defer
<head> <script> ... </script> </head> <body> <script> ... </script> </body>
Need help or want to share feedback? Join my discord community!
<head> <script src="/path/to/code.js"></script> </head> <body> <script src="/path/to/code.js"></script> </body>
The browser first downloads the HTML to the user and then starts parsing it. Inside the HTML, multiple external files are defined, e.g., stylesheets, images, and scripts. Before displaying the resources properly, the browser needs to download these files. This process stops the parsing of the website every time.
After the download of the resource finishes, the browser continues the parsing process. The following image shows this process:
With this image, we can see that the download and execution of the scripts interrupt the browser. But is loading the script in this position necessary? Sometimes yes, but most of the time, the scripts aren’t needed by the user immediately. Thus we need to move the downloading process and the execution to a later point or into the background.
If this guide is helpful to you and you like what I do, please support me with a coffee!
Now we know the cause of the performance problems (loading scripts when they are not necessary), and we can fight them. There are two HTML methods to do that, and we will look at them in the following section.
Speed up your website with async and defer
Defer will move the download of your script into the background and execute the script as soon as the site finished parsing. I will also respect the execution order of your scripts.
Use defer when scripts depend on each other!
You use defer by setting the defer attribute of your script tag:
<script defer src="/path/to/code.js"></script>
Async will move the download of your script into the background and execute the script as soon as the download is finished.
Use async when possible!
You use async by setting the async attribute of your script tag:
<script async src="/path/to/code.js"></script>
As a result, we found two methods on how to move the download process in the background and boost the performance:
- defer: Use defer when scripts depend on each other!
- async: Use async when possible!
I hope with this method you learned how to speed up your website! Let me know your results in the comments or via mail at firstname.lastname@example.org!