The other day, I got an email asking…
Great question! Here’s an over-simplified, handwavy explanation of how browsers load files…
- The HTML file downloads.
- The browser starts reading it, and rendering stuff in it in real time as it does.
- If it finds remote assets, it starts downloading them, two at a time, as it comes across them. Once they’re downloaded, they render.
Step 3 is where stuff gets “weird.”
Browsers are optimized to avoid repainting the UI whenever they can. If the browser finds a CSS file, it keeps downloading stuff but stops rendering until the CSS file is downloaded and parsed.
Because CSS changes how HTML is laid out, the browser wants to know the right way to do that to avoid painting the UI twice.
<script async src="script1.js"></script> <script defer src="script1.js"></script>
defer attribute tells the browser to download the file, but wait until all of the other stuff is done before running the file. The
async attribute tells the browser to download this file, but don’t stop downloading others while you do. The two can be used together.
So, the short answer is files are loaded in the order they appear in the HTML file.
The longer answer is … but it depends!