Ordering of Assets
In the second part of our multipart Frontend Optimization series I’ll cover my notes from Steve Souder’s “High Performance Websites” and “Even Faster Websites” books that can help optimize how you order and attach assets on your website.
- Put JS files at the bottom of the html if possible.
- Ensure that your stylesheets come last in the <head> (after any scripts attached in the <head>.)
- Make all CSS and JS files External. This leads to better caching of assets. If they’re inline they have to be downloaded every time.
- Don’t use @import it causes download order to be wacky in IE and if its used with <link> method than you don’t get parallel stylesheet downloads.
- Load Scripts in parallel. By default multiple JS scripts will not load in parallel. Each one loads one at a time and stops loading everything else while it does so. There is a table on stevesouders.com that shows browser buys indicators and techniques to load scripts in parallel. The best solution is to figure out whether or not the functionality in that JS file is something you want the busy indicator to show up for and use conditional comments to use the appropriate method for standards browsers and IE. You’ll also want to factor in load order. If you keep it for dependency reasons then its slower, if you don’t preserve load order its faster since the first script to download is executed immediately.
- Don’t scatter inline scripts. Each time you get to one it stops everything and just downloads that one script. Put them at the bottom when applicable.
- Since you only get around 2 connections per server (varies depending on browser), its best to spread out your assets on about 3 domains max including your current domain. This will ensure a greater number of parallel downloads, but be careful not to do too many dns requests as they’re hurtful to optimization.
- Ensure that all the js that you load for the initial onload event is needed. Most major sites don’t need 70% or more of their js. Anything not needed to display the initial page should be loaded later when its needed or just in the background.