You may visit websites from time to time where part of the page loads but it doesn’t look quite right or is not styled properly. Then in a split second after more of it has loaded it snaps into the expected form with full styling and looks fine.
Most developers get this right and avoid the problem without knowing why when building a site, then pull hairs out when they can’t figure out why that one page they are building keeps popping when it’s loading.
What causes Flash of Unstyled Content
The browser has a complex set of decisions to make when parsing the HTML, a lot of which center around what to wait for and what to show right away.
As style sheets usually contain critical styling data about how the page body is structured, element sizing and font styling, if this information has not been considered by the browser when it renderers the page it won’t appear as expected.
Once the style sheets have finished downloading the browser will then repaint the page with the relevant styling and the page will snap into place and look like it was expected to. That’s not how we want our pages to load!
It is not enough to just put the stylesheet above HTML to which it applies as it won’t always be downloaded fast enough to be considered and render the page correctly.
To get around this issue you’ll have to put the stylesheets inside the tag of the document. Most people do this by habit, but at times you will see some stylesheets inserted at the top of the document outside the . This subtle difference will make a major difference to the way the browser prioritizes and renders the page.
Going further: Avoiding Pseudo FOUC
We can go further and avoid other unwanted visual effects, such as popping or resizing of elements as the page loads.
A major culprit here is any image without its dimensions specified in it’s style attribute. If an image size or it’s container size is not specified, the rendering will consider it as taking up whatever space it does right when rendering the DOM. Once the image has loaded (and takes up more space) it will push everything around and below it to make room for the image.
Avoid this by coding in the CSS the height and width of these images so elements around them are positioned correctly, then the image will appear in its place when it has finished loading.
Also don’t forget to use neatShow.js to fade in your images beautifully!
All of these small things make a big difference to how your page first appears to the visitor and are good fundamentals to consider when building any webpage.