Load external CSS file in the body tag
To load an external CSS file in the <body>
tag, use JavaScript to create and append a link element dynamically:
This code injects the CSS link into the body, applying the mentioned styles.
Ins and outs of <link> placement
Traditional landscapes
By standard, the <link>
element that loads an external stylesheet is housed in the <head>
section of an HTML document. Conforming to this best practice mitigates the chances of a FOUC (Flash of Unstyled Content).
Deviation and caution
Technically, HTML5 does allow for a <link>
within the body, but such deployment can have unexpected effects, like delayed rendering or strange behavior, leading to a sub-optimal user experience.
Flexibility and trade-offs
Sure, JavaScript provides the flexibility to insert styles anywhere in the document, but realize that deviating from standard practices can yield maintenance and performance trade-offs.
Navigating unconventional paths
Unwanted complexity
Loading CSS into the body might dial up the complexity of your codebase. The increased complexity can catalyze elusive bugs and elevate the maintenance overhead.
Performance hiccups
Performance issues may crop up as well. Styles loaded late can prompt the page to re-render, ultimately bearing down on the user experience.
Justified exceptions
That being said, certain scenarios might necessitate embedding CSS within the body, like loading component-specific styles for a widget or an on-demand component in a single-page-application (SPA).
Consider alternatives for dynamic style modifications
Async and defer
You can load CSS asynchronously to prevent render-blocking. Use async
or defer
alongside script tags
:
CSS-in-JS
Look to CSS-in-JS libraries for granular, adaptive styling that injects styles into the body, offering a modern approach to spatial distribution of stylesheets.
Handling media queries and DOMContentLoaded
Conditionally load CSS via media queries or tether your non-essential style load to DOMContentLoaded
, fostering a quicker initial page load.
Performance enhancement techniques
For scenarios where performance is business-critical, consider fetching CSS asynchronously using the Fetch API or XHR. Insert the styles onto the page using a style tag.
Preloading styles
Preload vital styles using <link rel="preload" as="style">
. Optionally, load the styles using JavaScript when needed.
Inlining critical CSS
Inline your critical CSS into the <head>
. This prune the First Contentful Paint (FCP) time, delivering a speedier visual response to your users.
Was this article helpful?