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'; = 'all';
    css.href = path;



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


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 *