Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to hide HTML elements on page load before they are displayed?

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:

  1. HTML elements are not hidden initially using CSS
  2. 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).
like image 315
Undistraction Avatar asked Oct 12 '12 16:10

Undistraction


1 Answers

Like VKen, I prefer to use moderizr and Paul Irish's structure for the html element (which is what HTML5 Boilerplate uses)

<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->

Then in the style sheet:

.element-to-hide { display: none; }

.no-js .element-to-hide { display: block; }

Works great, no flash of elements disappearing.

like image 59
steveax Avatar answered Sep 16 '22 21:09

steveax