Eliminating FOUT In New Browsers

Code Snippets - Opacity and FadeToWhen creating plugins for WordPress, there are times when html is drawn to the page, but elements which that html depends on arrive late.  Javascript, font files or external content from YouTube or Google are all examples. This can cause FOUT (flash of unstyled text) or other unsatisfactory ugliness like stacks of images that when the javascript loads will be in a slider.

One way hide these messy elements is using the css property “opacity” and the jQuery function FadeTo.

For example: In my retina plus social icons plugin, I use an icon font. Because this is not the most important thing on the page, I load the font and javascript for the plugin in the footer.

This created a situation where the html for the sharebar and unicode for the icons were loaded with the rest of the page, but the font and javascript were loaded later. This created a big FOUT issue. The code calls for characters that don’t exist except in the icon font. When the page loaded, the icons appeared as strange characters from whichever font face was used for the content.

Here’s my solution:

In my CSS file I put this: .retina-icons{opacity: 0} This “hides” the div with the class of “retina-icons” by giving it an opacity of transparent. The div and its contents (the links and icon unicode) are all there, they’re just see-through. When everything in the window is finished loading (including my icon font and javascript), I tell jQuery to make “retina-icons” visible.

In my jQuery file I put this: $(window).load(function() { $('.retina-icons').fadeTo('600', 1); )};

This tells the browser if all the parts of the window (javascript and fonts too) are loaded, fade .retina-icons to opacity: 1 (which is 100% opacity). It also says fade it in .6 seconds (600 thousandths) so it fades in with some panache.

A side benefit is stability of the page layout during the loading of the page. By loading the html elements transparently, their locations in the page flow are preserved. This keeps the rest of the page from jumping around when the elements later become visible.

Some older browsers don’t support “opacity”. Check Can I Use to see the status of support for this technique.

I use this on lots of things that for whatever reason don’t look good until all their dependencies are loaded.

Happy Coding!