Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marchershey/139db0e8fd6f03a83578698409d333ce to your computer and use it in GitHub Desktop.
Save marchershey/139db0e8fd6f03a83578698409d333ce to your computer and use it in GitHub Desktop.
Prevent FOUC (Flash of unstyled content)

Prevent FOUC (Flash of unstyled content)

A flash of unstyled content (FOUC, also flash of unstyled text) is an instance where a web page appears briefly with the browser's default styles prior to loading an external CSS stylesheet, due to the web browser engine rendering the page before all information is retrieved.

What I like to do to prevent FOUC is to set the <html> tag to have a style of disply:none;. Then at the end of my javascript file (which is defered), I will fade in the <html> tag.

Example:

HTML Page

<html style="display:none;">
    ...
</html>

Javascript

/*
 * ------------------------------------------------------------------------------
 * FOUC Fix - Flash of Unstyled Content
 *
 * By default, the <html> tag is hidden to prevent the flash of unstyled content.
 * This simple fadeIn() function will allow the page to gracefully fade in once
 * all assets are loaded. This line of code must remain at the bottom of the js
 * assets.
 *
 * Source: https://gist.github.com/marchershey/139db0e8fd6f03a83578698409d333ce
 * ------------------------------------------------------------------------------
 */

$( 'html' ).fadeIn();

⚠️ Note: $( 'html' ).fadeIn(); must be the last line to run on your js assets. This ensures all other assets (including your stylesheet) will load before your page will be visible.

Contributing

If you feel there is a better, more simpler way to acheive this, please comment below.

Changelog

  • 1.0.0
    • Initial release
  • 1.0.1
    • Added syntax highlighting to codeblocks
    • Added changelog
  • 1.0.2
    • Made the version shield/badge link to the changelog
  • 1.0.3
    • Added source to the JS comment
@marchershey
Copy link
Author

Here's a theory of mine...

Let's say your body's background color is black (#000000), and the default browser viewport's color is white (#FFFFFF).

Since we're hiding the HTML tag, we're hiding everything inside it, including the body's background color, so in theory the background color should be white... and when javascript fades the body back in, it should flash from white to black.. but that's not the case (at least for me).

If this is happening to you, let me know. I'll look more into it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment