How to Add a CSS Stylesheet in Vanilla JavaScript

Follow me!

If you like this article, go ahead and follow me on Twitter:

Follow @getButterfly

The function below will dynamically inject a CSS stylesheet in the document head using vanilla JavaScript (no dependencies):

function v8LoadCSS(path) {
    console.log('Requesting ' + path + '... in progress');

    if (document.createStyleSheet) {
        try {
            console.log('Loading ' + path + '... in progress');

            document.createStyleSheet(path);
        } catch (e) {
            console.log('Failed dynamically loading stylesheet.');
        }
    } else {
        var css;

        css = document.createElement('link');
        css.rel = 'stylesheet';
        css.type = 'text/css';
        css.media = 'all';
        css.href = path;

        document.getElementsByTagName('head')[0].appendChild(css);
        console.log('Appending ' + path + ' to document head... success');
    }
}

Use it like this:

v8LoadCSS('https://www.example.com/path/to/assets/stylesheet.css');

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

πŸ‘‹ Added by Ciprian on Monday, January 8, 2018 in Blog, JavaScript. Last modified on Friday, January 5, 2018.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy