How to dynamically insert CSS files with JavaScript: performance effects

In this article we will see how to dynamically insert CSS files with JavaScript. This is a useful technique for performance.

We need to consider the scenario of a page initially without CSS styles. In this sense, we can add this style block to the head element.

<style>
        body {
            opacity: 0;
            transition: opacity 400ms linear;
        }

        .css-loaded {
            opacity: 1;
        }
</style>

Once the main styles are loaded by JavaScript, the CSS class .css-loaded will display the page content with the applied styles.

Our JavaScript code will use Promises to intercept the load and error events of the HTML link element added to the head.

const insertCSSStyles = (url = '') => {
    const link = document.createElement('link');
    link.href = url;
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.media = 'screen';
    document.querySelector('head').appendChild(link);

    return new Promise((resolve, reject) => {
      link.onload = () => { resolve(true); }
      link.onerror = () => { reject(false); }
    });
};

We can use our code in this way:

insertCSSStyles('styles.css')
        .then(() => {
          document.body.classList.add('css-loaded');
          // Rest of the application code
        })
        .catch((err) => {
          document.body.classList.add('css-loaded');
});

By doing so, the CSS styles will be loaded asynchronously without directly inserting the link element into the HTML source, thus speeding up the page loading.

Demo

JavaScript Dynamic CSS

Conclusion

Loading CSS files via JavaScript turns out to be a very useful technique for improving page loading performance, avoiding linking such resources directly in the HTML source.

Back to top