Inject CSS stylesheet as string using Javascript

JavascriptCssDomGoogle Chrome-Extension

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDan HlavenkaView Question on Stackoverflow
Solution 1 - JavascriptLiam NewmarchView Answer on Stackoverflow
Solution 2 - JavascriptJohn R PerryView Answer on Stackoverflow
Solution 3 - JavascriptIglesias LeonardoView Answer on Stackoverflow
Solution 4 - JavascriptPat CullenView Answer on Stackoverflow
Solution 5 - JavascriptGruberView Answer on Stackoverflow