Search code examples
csshtmlw3c

Correct way to include CSS after <head>


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.


Solution

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