I'm attempting to be able to import html fragments into my code as follows:
var links = document.querySelectorAll('link[rel="import"]');
fragments = {};
for (var i = 0; i < links.length; i++) {
var link = links.item(i);
if (definesFragment(link)) { // returns whether or not the import defines a valid fragment
var name = getTemplateName(link); // returns the file name from the link without the path or extension
var proto = Object.create(HTMLElement.prototype);
proto.createdCallback = function() {
var fragment = link.import.querySelector('fragment');
var clone = document.importNode(fragment, true);
var root = this.createShadowRoot();
root.appendChild(clone);
};
fragments[name] = document.registerElement('foo-' + name, { prototype: proto });
//console.log(new fragments[name]())
}
}
and then if I want to add this fragment to the page, I would write:
var frag = new fragments.bar();
document.body.appendChild(frag);
It seems to work correctly if there is only one fragment file defined, but as soon as there are multiple links, it modifies all previously registered elements to have the new fragment as their body.
For example, if I have two files:
bar.html:
<fragment>
bar
</fragment>
baz.html:
<fragment>
baz
</fragment>
If I un-comment the console.log at the bottom of the first script, it prints:
<foo-bar>
#shadowroot {
<fragment>
bar
</fragment>
}
</foo-bar>
<foo-baz>
#shadowroot {
<fragment>
baz
</fragment>
}
</foo-baz>
but if bar is included before baz, when I console.log(new fragments.bar()) later in the code it logs:
<foo-bar>
#shadowroot {
<fragment>
baz
</fragment>
}
</foo-bar>
I am curious as to why the previously registered elements are modified when I register another.
Thanks, Jake