To delve into the latest Web Components concepts, I am experimenting with the polyfills available at .
My focus is solely on utilizing the plain API without incorporating Polymer. Additionally, my goal is to ensure compatibility with the latest versions of Chrome, Firefox, and IE.
Currently, I am crafting a custom element called "user-profile" using a template labeled with the id "sdtemplate", which is then inserted into the Shadow DOM:
<template id="sdtemplate">
<style>
p { color: orange; }
</style>
<p>I'm in the Shadow DOM. My markup was stamped from a <template>.</p>
</template>
<script>
(function() {
function searchInImports(selector){
var links = document.querySelectorAll('link[rel="import"]');
for(var link in links){
if(links.hasOwnProperty(link)){
var results = links[link].import.querySelectorAll(selector);
if(results.length > 0){
return results;
}
}
}
}
var proto = Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
var t = searchInImports('#sdtemplate')[0];
var clone = document.importNode(t.content, true);
this.createShadowRoot().appendChild(clone);
}
}
});
document.registerElement('user-profile', {prototype: proto});
The element is successfully generated, but the application of CSS differs between IE, Firefox, and Chrome. While Chrome displays the CSS correctly—with only the <p>
tag within the template adhering to the styles due to the Shadow DOM—IE and Firefox exhibit CSS leakage, affecting other <p>
elements outside the template.
I attempted to enhance the CSS selector by adding the element name:
<style>
user-profile p { color: orange; }
</style>
Although this adjustment resolves the issue in IE and Firefox, it does not have the same effect in Chrome.
It seems that even with the polyfills, IE and Firefox lack proper support for the Shadow DOM.
Is there an uncomplicated method for implementing the Shadow DOM in supported browsers while having fallback options for those that do not support it?