Skip to content

Instantly share code, notes, and snippets.

@fimars
Created September 22, 2023 03:40
Show Gist options
  • Save fimars/037390ab3babb8984c0367a498314bd6 to your computer and use it in GitHub Desktop.
Save fimars/037390ab3babb8984c0367a498314bd6 to your computer and use it in GitHub Desktop.
const stylesheets = {};
export const injectStyles = ({ fileScopeId, css, mountNode = document.head }) => {
let stylesheet = stylesheets[fileScopeId];
if (!stylesheet) {
const styleEl = document.createElement('style');
styleEl.setAttribute('type', 'text/css');
stylesheet = stylesheets[fileScopeId] = styleEl;
if (mountNode !== document.head) {
styleEl.setAttribute('scoped', '');
}
mountNode.appendChild(styleEl);
}
stylesheet.innerHTML = css;
for (let i = 0; i < stylesheet.sheet.cssRules.length; i++) {
const rule = stylesheet.sheet.cssRules[i];
rule.selectorText = `.${mountNode.className} ${rule.selectorText}`;
stylesheet.sheet.deleteRule(i);
stylesheet.sheet.insertRule(rule.cssText);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment