I have found numerous partial answers to this question, but nothing that seems like a definitive answer. For such an important technique I find this a little strange.
How should I hide elements (using javascript) so that they do not appear briefly when the page loads before the JS has a chance to hide them? I don't want to set them to hidden initially with CSS as if a user doesn't have Javascript, they will see nothing.
To be clear. I'm not asking how to handle displaying content to users who don't have JS. That is an entirely different subject. I just want a reliable way to hide HTML elements before they are displayed.
So my requirements:
- HTML elements are not hidden initially using CSS
- If JS is available, these elements are hidden so that they are never displayed, not even for an instant. This means hiding them from JS loaded at the end of the body is out).
Use a descendent combinator and make the body a member of a class as soon as possible.
Like VKen, I prefer to use moderizr and Paul Irish's structure for the
html
element (which is what HTML5 Boilerplate uses)Then in the style sheet:
Works great, no flash of elements disappearing.
you could do a
<noscript>
tag and overwrite the initial css for those with javascript disabledA solution is to use javascript to include an optional CSS file in which you hide those divs.
Put this in your
HEAD
section :And in hiding.css :
If you don't have additional css to set, you may also more simply inline the css rule in javascript (still in the HEAD) :
If Javascript isn't available, the divs won't be hidden. And if it is available, the CSS will be used to hide the div before they're displayed.