When optimizing a page you’re obviously thinking about where to add different assets on it. Stuff that is needed up front is placed at the top and stuff that is needed later can be placed further down. After all, we want the page to show something as fast as possible!
Performance That Matters
The percieved performance in this case is the most important factor. We therefore want the page to load progressively, meaning: The page renders from top to bottom as content is being downloaded.
Lets say you’re building an image gallery to show off your fabolous collection of Rainbow Unicorns. When the user clicks a unicorn a lightbox will open and display a bigger image of it.
Now, the CSS for the lightbox isn’t needed for rendering the page. It’s actually not needed until the user clicks an image. Therefore we could include it at the bottom of the page to let other content load first right.
– You know so that the page will render faster?
Wrong! Contrary to common sense it will actually delay the rendering of the page in a lot of web browsers.
But why does it delay the rendering? Keeping the browser from downloading it before other content ought to make the rendering faster. This is really counter intuitive at first glance, but listen to this:
The browser doesn’t want to risk having to re-render the page, it therefore waits until all CSS is loaded before rendering anything!
Fortunately there’s a really simple solution to this. Just follow this simple rule: Include all CSS in the <head> of the page.
Note: This article has previously been published on Code Crafting Blueprints.