Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 567
Jon Cox Avatar asked Jul 21 '11 16:07

Jon Cox


2 Answers

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 {}

like image 101
edeverett Avatar answered Oct 05 '22 05:10

edeverett


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>
like image 30
Michael Berkowski Avatar answered Oct 05 '22 05:10

Michael Berkowski