KemanoThief
KemanoThief

Reputation: 617

What's the best way to include CSS for JS-enabled browsers?

What's the best practice way to include a CSS file in your HTML page on JS-enabled browsers only? I heard that using document.write is highly discouraged.

<head>
  <!-- Other head stuff here -->
  <script>document.write('<link rel="stylesheet" href="assets/stylesheets/layout_js-only.css">');</script>
</head>

Upvotes: 1

Views: 45

Answers (2)

abigwonderful
abigwonderful

Reputation: 1927

would a solution like this be what you are looking for: Use some CSS only if user has JavaScript enabled

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

Upvotes: 2

Mike Cluck
Mike Cluck

Reputation: 32511

Definitely don't use document.write. You can do the same work as document.write by creating new elements and appending them to the <head>.

var stylesheet = document.createElement('link');
stylesheet.rel = 'stylesheet';
stylesheet.href = 'assets/stylesheets/layout_js-only.css';
document.querySelector('head').appendChild(stylesheet);

I'd also suggest placing this code in the <body> to ensure the <head> is properly loaded.

Upvotes: 1

Related Questions