Fading a Page In on Load, the Simple Way

Louis Lazaris has a small technique for making a page fade in as it loads. The sequence has three stages, and none of them require much code.

  1. A CSS class that sets opacity: 0 is applied to the body immediately, via JavaScript.
  2. All of the page's JavaScript is allowed to run to completion.
  3. The body is revealed by transitioning it back to opacity: 1.

For the moment when the reveal happens, Louis demonstrates a callback method and also points out that you could wait on window.load or a DOM Ready event. Another option is simply making the line that switches the className to visible the very last statement the script executes.

Louis freely admits the approach runs against current fashion, and he addresses the tradeoff directly:

I know nowadays we're obsessed in this industry with gaining every millisecond in page performance. But in a couple of projects that I recently overhauled, I added a subtle and clean loading mechanism that I think makes the experience nicer, even if it does ultimately slightly delay the time that the user is able to start interacting with my page.

The contrast is with techniques like font-display: swap;, whose whole purpose is to paint text as quickly as possible, FOUT be damned, rather than the more relaxed alternatives. A slight delay to interaction is the price of the fade. Direct Link →

CSS-Tricks star logo