简体   繁体   中英

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 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.

A solution is to use javascript to include an optional CSS file in which you hide those divs.

Put this in your HEAD section :

<script>document.write('<link rel="stylesheet" type="text/css" href="hiding.css"/>');</script>

And in hiding.css :

div.mySelector {
   display:none;
}

If you don't have additional css to set, you may also more simply inline the css rule in javascript (still in the HEAD) :

<script>
document.write('<style type="text/css">div.mySelector {display:none; }</style>');
</script>

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.

Use a descendent combinator and make the body a member of a class as soon as possible.

<style>
    /* js only element */
    .js foo { display: none; }
</style>
</head>
<body>
<script> document.body.className += " js"; </script>

你可以做一个<noscript>标签并覆盖那些禁用了javascript的人的初始css

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM