Correct way to include CSS after <head>

Alex picture Alex · May 19, 2012 · Viewed 18.2k times · Source

Apparently adding <link rel="stylesheet" ... in the document body is considered a bad practice by W3C standards. The same for adding <style> blocks in the body...

So are there any standard-compliant solutions to add CSS outside of the <head> tag? Like at the end of the document.

Answer

Madara&#39;s Ghost picture Madara's Ghost · May 19, 2012

If you only want to include your CSS styles on a specific events, there's nothing stopping you from doing so at the head:

var linkElement = document.createElement("link");
linkElement.rel = "stylesheet";
linkElement.href = "path/to/file.css"; //Replace here

document.head.appendChild(linkElement);

This has the added benefit of adding your stylesheet in an async way, which doesn't block the browser from downloading anything else.