- CSS blocks rendering
Now, while this might instill a sense of “wat” in you, it’s all done for good (and smart) reasons, and it’s also be something that all front-end devs should be aware of.
CSS blocks page rendering because browsers want to render things as they get to them and in the correct order. Browsers won’t render pages until they know all the styles available, meaning they don’t have to go back and apply new styles to already-rendered elements, causing an expensive (and jarring) redraw.
The HTTP/1.1 spec makes the suggestions that browsers should use a maximum of two connections at a time to each domain.
Clients that use persistent connections SHOULD limit the number of simultaneous connections that they maintain to a given server. A single-user client SHOULD NOT maintain more than 2 connections with any server or proxy. A proxy SHOULD use up to 2*N connections to another server or proxy, where N is the number of simultaneously active users. These guidelines are intended to improve HTTP response times and avoid congestion.
On the assumption that browsers download a max of two assets from one domain, we can crank up the amount of assets we can download at once by using a Content Delivery Network. If we’re downloading a stylesheet and an image at the same time from
http://www.coog.ie/, we can download a stylesheet and three images at the same time by using
http://static2.coog.ie/, with each serving two files, alternating between the two domains.
It does this for two reasons:
- The script being called could alter the DOM which means the browser will have to handle the changes before it can proceed with anything else.
- Typically, scripts need to be loaded, and executed, in a specific order.
Unfortunately, not all scripts can be moved to the end of the document. If a script uses
<head> is loaded after any CSS we have.
tl;dr – Putting the knowledge to use
So, using the things we’ve learned, we now know that to improve performance on the front-end we should do the following:
- Place CSS at the top, in the
- Use a CDN to increase the number of parallel downloads