How to Add a CSS Stylesheet in Vanilla JavaScript

Ciprian on Monday, January 8, 2018 in JavaScript DOM

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

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

Leave a Reply

Your email address will not be published. Required fields are marked *