This tutorial describes a way to avoid a flash of unstyled content that sometimes occurs when applying styles with JavaScript on page load. The problem is most evident when there is some content that needs to be hidden initially and when the document is large or complex. We can see an example of the problem on this test page.
The page is a copy of a previous entry on this blog with over 140 comments—quite a lot of content. Look for the bright yellow background before the page finishes loading. That's the part that is supposed to be hidden from the start — a simple unordered list, <ul id="flash">.
In pages with a more reasonable length, the standard jQuery code would work just fine:
JavaScript:
$
(document
).
ready(function() {
});
But in this page there is a whole lot of document that has to be ready before anything inside the $(document).ready() function can be executed. Too much, in fact. And putting the <script> tags just inside the closing </body> tag doesn't help either. No, using JavaScript to hide elements like this just won't work unless the scripts are placed in the HTML immediately following the elements they're hiding.
Read the rest of this entry »