Inject CSS stylesheet as string using Javascript

76,792

Solution 1

There are a couple of ways this could be done, but the simplest approach is to create a <style> element, set its textContent property, and append to the page’s <head>.

/**
 * Utility function to add CSS in multiple passes.
 * @param {string} styleString
 */
function addStyle(styleString) {
  const style = document.createElement('style');
  style.textContent = styleString;
  document.head.append(style);
}

addStyle(`
  body {
    color: red;
  }
`);

addStyle(`
  body {
    background: silver;
  }
`);

If you want, you could change this slightly so the CSS is replaced when addStyle() is called instead of appending it.

/**
 * Utility function to add replaceable CSS.
 * @param {string} styleString
 */
const addStyle = (() => {
  const style = document.createElement('style');
  document.head.append(style);
  return (styleString) => style.textContent = styleString;
})();

addStyle(`
  body {
    color: red;
  }
`);

addStyle(`
  body {
    background: silver;
  }
`);

IE edit: Be aware that IE9 and below only allows up to 32 stylesheets, so watch out when using the first snippet. The number was increased to 4095 in IE10.

2020 edit: This question is very old but I still get occasional notifications about it so I’ve updated the code to be slightly more modern and replaced .innerHTML with .textContent. This particular instance is safe, but avoiding innerHTML where possible is a good practice since it can be an XSS attack vector.

Solution 2

Thanks to this guy, I was able to find the correct answer. Here's how it's done:

function addCss(rule) {
  let css = document.createElement('style');
  css.type = 'text/css';
  if (css.styleSheet) css.styleSheet.cssText = rule; // Support for IE
  else css.appendChild(document.createTextNode(rule)); // Support for the rest
  document.getElementsByTagName("head")[0].appendChild(css);
}

// CSS rules
let rule  = '.red {background-color: red}';
    rule += '.blue {background-color: blue}';

// Load the rules and execute after the DOM loads
window.onload = function() {addCss(rule)};

fiddle

Solution 3

Have you ever heard of Promises? They work on all modern browsers and are relatively simple to use. Have a look at this simple method to inject css to the html head:

function loadStyle(src) {
    return new Promise(function (resolve, reject) {
        let link = document.createElement('link');
        link.href = src;
        link.rel = 'stylesheet';

        link.onload = () => resolve(link);
        link.onerror = () => reject(new Error(`Style load error for ${src}`));

        document.head.append(link);
    });
}

You can implement it as follows:

window.onload = function () {
    loadStyle("https://fonts.googleapis.com/css2?family=Raleway&display=swap")
        .then(() => loadStyle("css/style.css"))
        .then(() => loadStyle("css/icomoon.css"))
        .then(() => {
            alert('All styles are loaded!');
        }).catch(err => alert(err));
}

It's really cool, right? This is a way to decide the priority of the styles using Promises.

Or, if you want to import all styles at the same time, you can do something like this:

function loadStyles(srcs) {
    let promises = [];
    srcs.forEach(src => promises.push(loadStyle(src)));
    return Promise.all(promises);
}

Use it like this:

loadStyles([
    'css/style.css',
    'css/icomoon.css'
]);

You can implement your own methods, such as importing scripts on priorities, importing scripts simultaneously or importing styles and scripts simultaneously. If i get more votes, i'll publish my implementation.

If you want to learn more about Promises, read more here

Solution 4

I had this same need recently and wrote a function to do the same as Liam's, except to also allow for multiple lines of CSS.

injectCSS(function(){/*
    .ui-button {
        border: 3px solid #0f0;
        font-weight: bold;
        color: #f00;
    }
    .ui-panel {
        border: 1px solid #0f0;
        background-color: #eee;
        margin: 1em;
    }
*/});

// or the following for one line

injectCSS('.case2 { border: 3px solid #00f; } ');

The source of this function. You can download from the Github repo. Or see some more example usage here.

My preference is to use it with RequireJS, but it also will work as a global function in the absence of an AMD loader.

Solution 5

I think the easiest way to inject any HTML string is via: insertAdjacentHTML

// append style block in <head>

const someStyle = `
<style>
    #someElement { color: green; }
</style>
`;

document.head.insertAdjacentHTML('beforeend', someStyle);
Share:
76,792
Dan Hlavenka
Author by

Dan Hlavenka

Apparently, this user prefers to keep an air of mystery about them.

Updated on July 08, 2022

Comments

  • Dan Hlavenka
    Dan Hlavenka almost 2 years

    I'm developing a Chrome extension, and I'd like users to be able to add their own CSS styles to change the appearance of the extension's pages (not web pages). I've looked into using document.stylesheets, but it seems like it wants the rules to be split up, and won't let you inject a complete stylesheet. Is there a solution that would let me use a string to create a new stylesheet on a page?

    I'm currently not using jQuery or similar, so pure Javascript solutions would be preferable.

  • Dan Hlavenka
    Dan Hlavenka about 11 years
    I would have come up with innerHTML eventually, but the second snippet you provided is really cool!
  • angry kiwi
    angry kiwi over 10 years
    Both snippets give me error: TypeError: document.body is null document.body.appendChild(node);
  • Dan Hlavenka
    Dan Hlavenka almost 10 years
    Your method of using a multi-line comment is... interesting. I'm not sure how "good" an idea it is, but it sure is interesting.
  • djjeck
    djjeck about 9 years
    I would say it's a dangerous misuse. CSS allows multiline comments too, so be careful when you copy-paste styles from existing stylesheets.
  • brandito
    brandito over 5 years
    Couldn't you append to the node's innerHTML to add continuously? e.g something like node.innerHTML = node.innerHTML + " " + str;?
  • Pascal Ganaye
    Pascal Ganaye over 3 years
    Interesting indeed. Here you wait for the end of a css to load the next though Wouldn't it be more efficient to load it all in one go?
  • Iglesias Leonardo
    Iglesias Leonardo over 3 years
    It is definitely more efficient to load them all at once. However, in some cases there may be a need to assign a certain priority. I have published a simultaneous style load implementation.
  • user1020069
    user1020069 almost 3 years
    I guess this is better solution because promises will run asynchronously and not be render blocking as opposed to the accepted solution
  • Francisco Luz
    Francisco Luz about 2 years
    All the other answers add complication to a simple thing. This is elegant because it is simple.