Load CSS with JavaScript and wait for it to load

OpenJavaScript 0

Last updated: November 15, 2023.

Sometimes it can be useful to load CSS dynamically with JavaScript.

You can do this by creating and appending a <link> element in the HTML <head> section:

const condition = true;

if (condition) {
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = 'http://some.website/styles.css';
    document.head.appendChild(link);
}

The stylesheet starts loading as soon as it is appended to the page.

If you want to wait until the stylesheet has loaded to do something, you can wrap the process of appending the <link> element to the DOM in a promise.

To resolve or reject the promise when the stylesheet loads (or fails to load), you can perform this action inside an onload and onerror attribute added to the attributes on the <link> element:

const condition = true;

if (condition) {
    new Promise((resolve, reject) => {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = 'http://some.website/styles.css';
        link.onload = () => { resolve() };
        link.onerror = () => { reject() };
        document.head.appendChild(link);
    })
    .then(() => {
        console.log("The stylesheet loaded");
    })
    .catch(() => {
        console.error("Error loading stylesheet");
    });
}
Tags: