Last active
July 24, 2016 16:16
-
-
Save caub/b1994561abbf4a64a5c129577d89dfa0 to your computer and use it in GitHub Desktop.
<style scoped> polyfill
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
let scopedRule = (scope, {selectorText: selector='', cssText:css, style: {cssText}={}, styleSheet, cssRules, media}) => | |
styleSheet? // @import rules | |
scopedRules(scope, styleSheet.cssRules): | |
cssRules && media? // @media rules | |
`@media ${Array.from(media).join(',\n')} {${scopedRules(scope, cssRules)}}`: | |
!selector||selector.startsWith(':root')||selector.startsWith('body')? | |
css: | |
`${selector.split(',').map(s=>`${scope} ${s}`).join(', ')} {${cssText}}`; | |
//`${selector.replace(/([^,]+)/g, (_, s) => `${scope} ${s}`)} {${cssText}}`; | |
let scopedRules = (scope, rules=[]) => Array.from(rules, r=>scopedRule(scope, r)).join('\n'); | |
let styles = document.querySelectorAll('style[scoped], link[scoped]'); | |
for (let i=0, style; i<styles.length, style=styles[i]; i++) { | |
//if (style.tagName==='STYLE' && /firefox/i.test(navigator.userAgent)) continue; | |
let scoped = style.getAttribute('scoped'), id = style.parentNode.id, cls = style.parentNode.classList[0] || 's_'+i; | |
let scope = scoped&&scoped!=='true' ? // use it as prefix | |
scoped : | |
(id ? '#'+id : '.'+cls); | |
let el = document.createElement('style'); | |
el.type = 'text/css'; | |
el.textContent = scopedRules(scope, style.sheet.cssRules); | |
style.parentNode.replaceChild(el, style); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment