Explain Codes LogoExplain Codes Logo

How to load up CSS files using Javascript?

javascript
prompt-engineering
functions
promises
Nikita BarsukovbyNikita Barsukov·Sep 28, 2024
TLDR

To instantly inject a CSS file into your document, create a <link> element with JavaScript:

var cssLink = document.createElement("link"); cssLink.rel = "stylesheet"; cssLink.href = "style.css"; // Swap this with your CSS file name document.head.appendChild(cssLink);

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:

// We don't want the CSS party to turn into a clone party! var existingSheets = document.getElementsByTagName("link"); var targetStyleSheet = "path/to/style.css"; // Absolute path for (var i = 0; i < existingSheets.length; i++) { if (existingSheets[i].href === targetStyleSheet) return; // CSS is already rocking this party } var cssLink = document.createElement("link"); cssLink.rel = "stylesheet"; cssLink.href = targetStyleSheet; document.head.appendChild(cssLink);

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:

// A clear address for your CSS 'party invitation' cssLink.href = "https://yourdomain.com/path/to/style.css";

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:

Access-Control-Allow-Origin: *

Compatibility is key

To bolster browser support, including for old-but-gold IE6, use the setAttribute method:

cssLink.setAttribute('type', 'text/css'); cssLink.setAttribute('href', targetStyleSheet);

Encode the CSS path and use it as an ID for the link to easily pinpoint or replace it later:

cssLink.id = encodeURIComponent(targetStyleSheet);

When jQuery is your cup of tea

If you're a fan of shorter jQuery syntax, it can elegantly simplify the task:

// jQuery 'does the job' in a swaggy style $('head').append($('<link rel="stylesheet" type="text/css" href="path/to/style.css" />'));

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:

initiateThePartyBeforeTheRockbandArrives(cssLink, document.head.firstElementChild);

Handling asynchronous behavior

If you prefer to keep your activities non-blocking, you could utilize Promises or the fetch API:

fetch('path/to/style.css') // Your party's location .then(response => response.text()) // Open the invitation .then(style => { var cssBlob = new Blob([style], { type: 'text/css' }); var fancyInvitation = URL.createObjectURL(cssBlob); var cssLink = document.createElement('link'); cssLink.rel = 'stylesheet'; cssLink.href = fancyInvitation; // Here's your invitation! document.head.appendChild(cssLink); });

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:

if (document.createStyleSheet) { document.createStyleSheet('path/to/style.css'); // IE's got its own swag } else { var cssLink = document.createElement("link"); cssLink.rel = "stylesheet"; cssLink.href = 'path/to/style.css'; document.head.appendChild(cssLink); }

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:

cssLink.onerror = function() { console.error("This CSS ain't partying:", cssLink.href); };