How to dynamically append a CSS file

πŸ‘‹ Ciprian on Monday, September 18, 2017 in Blog
Last modified on Friday, September 15, 2017

Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

This code snippet allows you to dynamically append a CSS file to your document’s head. It can be used inside any JavaScript code or for custom A/B experiments.

JavaScript

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');
    }
}

Usage

v8LoadCSS('/path/to/stylesheet.css');

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

πŸ‘‹ Added by Ciprian on Monday, September 18, 2017 in Blog. Last modified on Friday, September 15, 2017.

Leave a Reply

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

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

Privacy Policy