I'm using jQuery in the examples below, but my question applies more generally to any situation where javascript is used to display something that would be missed if javascript wasn't enabled.

Let's say I want to fade in some text when the page loads:

.fade-in { opacity:0; }

<div class="fade-in">FOOBAR</div>

$('.fade-in').fadeIn();

But what if the client doesn't have javascript enabled?

I don't want the text to remain invisible, so maybe I set the CSS to the end state as a fallback, and then UN-set it with javascript prior to the animation. This way, users without javascript just see normal text (without a fadeIn), and users with JS see the fade.

.fade-in { opacity:1; }

<div class="fade-in">FOOBAR</div>

$('.fade-in').css('opacity', 0);
$('.fade-in').fadeIn();

This works, but in most cases it will result in an unpleasant "flicker" between when the CSS display property is set and when the javascript unsets it. In the above example, a user with javascript working normally would see the "FOOBAR" appear for a split second, then vanish, then fade in.

Is there a best practice for this which doesn't result in the flicker OR sacrificing no-JS users?

Please do not fixate on the trivial example above. That is just to demonstrate the concept. I'm looking for a broader strategy for handling these cases. Also, I don't want to debate the merits of progressive enhancement or whether it is or isn't necessary to support the no-JS users. That's a question for another thread(s).

Update: I know tools like Modernizr can be used to add .no-js classes, etc but I'd prefer a solution that does not rely on these libraries.

没有正确的解决方案

其他提示

If the user doesn't have JS enabled, create a stylesheet for him:

<head>
scripts
<noscript><link href="no-js.css" /> </noscript>
</head>

Use <noscript></noscript> tags

I wonder, would something like this work?

<body>

<noscript>
<div class="no-js">
</noscript>

...

<noscript>
</div>
</noscript>

</body>

The idea is to keep all the CSS in one stylesheet by conditionally wrapping the elements in .no-js class without requiring Modernizr.

Here is my best bet for you: use a no-js and a js classes on your html element:

<html class="no-js">
<head>
    <title>...</title>
    <!-- Change "no-js" class to "js" in the html element -->
    <!-- This must appear high in your page to avoid FOUC effect -->
    <script>(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)</script>
</head>
<body>
    ...
</body>
</html>

This way, your CSS could look like this:

/* The item first appears with opacity=1, then disappears when the no-js class is removed */
.no-js .fade-in { opacity: 1; }
.fade-in { opacity: 0; }

This is almost what tools like Modernizr are doing but very simplified here :)

Credits goes to Paul Irish: http://www.paulirish.com/2009/avoiding-the-fouc-v3/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top