1

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>
KemanoThief
  • 545
  • 5
  • 22
  • CSS is supposed to be loaded before the , and the only way to do that dynamically is via document.write(). a plain DOM link tag addition to might be a little more philosophically cleaner JS-wise, but it will also be async, which can cause a FAUC. really the best way (balancing theory and real-world) is to hard-code any sheets you'll need as tags in the and then disable/un-disable certain ones via JS. – dandavis May 23 '16 at 20:58

2 Answers2

2

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.

Community
  • 1
  • 1
abigwonderful
  • 1,267
  • 10
  • 10
1

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.

Community
  • 1
  • 1
Mike Cluck
  • 28,921
  • 12
  • 72
  • 85