Shady DOM is a lightweight polyfill that emulates the JavaScript-facing behavior of Shadow DOM where native support is unavailable. It helps protect a component’s internal DOM from outside querying and manipulation, but it does not provide equivalent CSS encapsulation; ShadyCSS addresses that separate problem. section 10.3 section 8.3
A practical Shady DOM workflow involves:
- Load the Web Components polyfill bundle or install it through npm. section 8.3
- Define a custom element that attaches an open shadow root and initializes its internal HTML in connectedCallback. section 8.3
- Test external DOM access, such as assigning innerHTML after connection; unsupported browsers receive behavior comparable to native Shadow DOM. section 8.3
- Treat CSS separately, because emulating style scoping is harder and requires ShadyCSS with additional setup. section 10.3
Listing 8.8. Component with polyfill
<html>
<head>
<script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.0.0/
webcomponents-loader.js"></script> #1
<script>
class SampleComponent extends HTMLElement {
constructor() {
super();
this.root = this.attachShadow({mode: 'open'});
}
connectedCallback() {
if (!this.initialized) {
this.root.innerHTML = 'setting some HTML';
this.initialized = true;
}
}
}
if (!customElements.get('sample-component')) {
customElements.define('sample-component', SampleComponent);
}
</script>
</head>
<body>
<sample-component></sample-component>
<script>
setTimeout(function() {
document.querySelector('sample-component').innerHTML =
'Component is hijacked';
}, 500); #2
</script>
</body>
</html>
Use the component listing to trace polyfill loading, shadow-root creation, lifecycle initialization, and the cross-browser access test. section 8.3
