FLASH SALE Get 20% OFF everything using the coupon code: FLASH20 View WordPress Plugins →

How to Add a CSS Stylesheet in Vanilla JavaScript

on in JavaScript DOM
Last modified on

The function below will dynamically inject a CSS stylesheet in the document’s <head> using Vanilla JavaScript (no dependencies).

When is this technique useful?

Example #1

Let’s say you are loading additional content dynamically, based on user actions. This content needs a stylesheet, but you don’t want to add the CSS to your main stylesheet, especially if the dynamic content is not going to be accessed frequently (such as on evey user visit).

In this case, you can trigger the stylesheet loading only when you need it.

Example #2

Another scenario is when using various components in a single page application. Your main stylesheet is whatever you need on your main screen (critical CSS) and the rest is loaded based on active components.

function gb_load_css(path) {
    let css = document.createElement('link');
    css.rel = 'stylesheet';
    css.media = 'all';
    css.href = path;

    document.getElementsByTagName('head')[0].appendChild(css);
}

Usage

Use it like this (make sure the path is absolute):

gb_load_css('https://www.example.com/path/to/stylesheet.css');

Also read how to load a JavaScript file on the fly.

Related posts