Loading CSS Stylesheet on Demand Through Its disabled Attribute

Use-Cases of this tutorial

  • Know how to load a stylesheet dynamically with Javascript (without creating a new <link> element).
  • Know about the "disabled" attribute that can be applied to a stylesheet tag.

A stylesheet can include the "disabled" attribute in its markup to prevent it from being downloaded on page load. Later when the stylesheet needs to loaded on demand, its "disabled" attribute can be removed with Javascript.

Sometimes we may need to load a stylesheet dynamically rather than on page load. Until now this was done with Javascript by creating a new <link> element.

// create new link element
var link = document.createElement('link');

// set properties of link
link.href = 'css/common.css';
link.rel = 'stylesheet';
link.type = 'text/css';

// append link element to html
document.body.appendChild(link);

However modern browsers have made this simpler now.

The disabled attribute can be applied to the markup of the stylesheet element <link rel="stylesheet">, and this effectively disables the stylesheet from loading during page load, and prevent containing styles from being applied.

<!-- this CSS file will not be downloaded by browser on page load -->
<link rel="stylesheet" type="text/css" href="css/common.css" id="common-css" disabled>

Only when the disabled attribute is removed or set to false (using Javascript), then the CSS stylesheet will be downloaded by the browser and style changes will be applied to the page.

// now CSS stylesheet with id "#common-css" will be loaded and styles applied
document.querySelector("#common-css").removeAttribute('disabled');

// alternate
document.querySelector("#common-css").setAttribute('disabled', false);

This method is way easier than creating a new <link> element with Javascript, and helps to keep markup separate from the code.

Loading CSS Files with Javascript
Loading Comments