开发者

Use some CSS only if user has JavaScript enabled

In order for my webpage to degrade gracefully, I have some CSS that should only be loaded if its corresponding JavaScript will function.

What is the simplest way to load 开发者_StackOverflow中文版local CSS if and only if the browser has JavaScript enabled?

Also it's quite a big block of CSS, so I'd rather not have to write a JavaScript line to add each attribute. (Oh, and if necessary I can use jQuery).


Set a class on the body tag of "noJS". Then use Javascript to remove that class.

For the CSS rules that you want to be used when no JS is present, just use .noJS .myRules {}


In the <head> you can include it with document.write(). I've never tried this, but it should work in theory. No script execution means no stylesheet loaded.

<head>
  <script type='text/javascript>
   document.write("<link rel='stylesheet' href='your.css' media='whatever />");
  </script>
</head>


You have a few options.

The one I like is to add the following code to the body tag.

<body id="no-js"><script>document.body.id="js"</script>

Then I can target #no-js and #js from my master CSS.

An additional option is to load an extra stylesheet with JavaScript, but that will slow down you initial load, which I try to avoid.


Check out the body conditionals for html5 boilerplate to see how to employ modernizr.

Also good example here: http://webdesignernotebook.com/css/how-to-use-modernizr/

Then write your css selectors for .no-js .addl-selector {}


I simply do this:

document.documentElement.className = "js"

This adds class js to <html> tag, then you can target your elements by css using:

.js #someid{}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜