How to load up CSS files using Javascript?
To instantly inject a CSS file into your document, create a <link>
element with JavaScript:
The stylesheet you specified is applied to your page as soon as the script executes.
Checking for existing stylesheets
Before adding a stylesheet dynamically, ensure it's not already included to prevent redundancy:
Advice on setting stylesheet paths
Give absolute paths when referencing your CSS files. This ensures the correct stylesheet is loaded irrespective of the current page's URL structure:
Cross-origin gotcha!
If your CSS file is hosted on a different domain than your website, ensure that the server serving your CSS file has the appropriate CORS headers set, so web browsers don't ruin your stylesheet party
:
Compatibility is key
To bolster browser support, including for old-but-gold IE6, use the setAttribute
method:
Encode the CSS path and use it as an ID for the link to easily pinpoint or replace it later:
When jQuery is your cup of tea
If you're a fan of shorter jQuery syntax, it can elegantly simplify the task:
Preventing FOUC – the party pooper
To avoid a Flash of Unstyled Content (FOUC), a real party pooper in your CSS party, ensure to include your CSS before loading any heavyweight JavaScript libraries:
Handling asynchronous behavior
If you prefer to keep your activities non-blocking, you could utilize Promises or the fetch API:
A tip for the IE loyalists
Internet Explorer occasionally throws curveballs when dynamically inserting stylesheets. For IE-specific handling, you might want to check out the document.createStyleSheet()
method:
Let's deal with those pesky errors
When inserting styles in a dynamic fashion, remember to handle errors that might crop up during stylesheet loading:
Was this article helpful?