Categories
JavaScript Answers

How to load CSS asynchronously with JavaScript?

Spread the love

Loading CSS asynchronously with JavaScript typically involves creating a <link> element dynamically and appending it to the document’s <head> element.

For example, we write:

function loadCSS(url) {
    return new Promise((resolve, reject) => {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = url;
        link.onload = () => resolve();
        link.onerror = () => reject(new Error(`Failed to load CSS: ${url}`));
        document.head.appendChild(link);
    });
}

// Usage
loadCSS('styles.css')
    .then(() => {
        console.log('CSS loaded successfully');
        // You can perform additional actions after the CSS has loaded
    })
    .catch(error => {
        console.error('Error loading CSS:', error);
    });

In this example, the loadCSS function takes a URL parameter for the CSS file you want to load.

It returns a Promise, which resolves when the CSS has successfully loaded and rejects if there’s an error.

Inside the function, a new <link> element is created with the rel attribute set to 'stylesheet' and the href attribute set to the provided URL.

Event listeners are attached to handle the load and error events of the <link> element.

If the CSS loads successfully, the resolve function of the Promise is called.

If there’s an error loading the CSS, the reject function is called with an error message.

Finally, the <link> element is appended to the <head> of the document.

You can use this function to load CSS asynchronously in your JavaScript code.

This can be useful for optimizing page loading performance, especially when the CSS is not critical for initial rendering.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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