Skip to content

Instantly share code, notes, and snippets.

@dy
Created September 15, 2020 13:36
Show Gist options
  • Save dy/2124c2dfcbdd071f38e866b85436c6c5 to your computer and use it in GitHub Desktop.
Save dy/2124c2dfcbdd071f38e866b85436c6c5 to your computer and use it in GitHub Desktop.
Scoped script polyfill
<!DOCTYPE html>
<script id='scoped-script'>
let i = 0;
(new MutationObserver(rx=>rx.forEach(({target:s}) => {
if (s.tagName !== 'SCRIPT' || s.scoped || !s.hasAttribute('scoped')) return
s.scoped=true
if (!s.id) s.id='__s'+i++
s.innerHTML=`(function(){${s.innerHTML}}).call(document.getElementById('${s.id}').parentNode)`
}))).observe(document, {childList:true,subtree:true,attributes:true,attributeFilter:['scoped']})
</script>
<custom-element>
<script scoped>
console.log(this)
</script>
</custom-element>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment