I'm learning web components with a shadow root and can't seem to find on google if loading external stylesheets is possible with out-of-the-box code? I am NOT using polymer or any other web component library (yet). Code below:
<script src="../../libs/jquery-2.1.1.min.js"></script>
<script>
var hollaProto = Object.create(HTMLElement.prototype);
hollaProto.createdCallback = function () {
var shadow = this.createShadowRoot();
var content = document.querySelector('link[rel=import]').import.querySelector("div");
$("button[data-command=holla]", content).on("click", function () { alert("Holla!"); });
shadow.appendChild(content);
};
var hollaWidget = document.registerElement("holla-back", {
prototype: hollaProto
});
</script>
<div class="holla-back">
<button data-command="holla">Holla!</button>
</div>
If I put my link tag up top, above the first script tag, I style the whole web age, but not the web component.
If I put it under div.holla-back
it doesn't style anything.
How do you use external stylesheets with web components?
Link tags are inert in Shadow DOM according to the spec. However, you can use @import
, though that has its own performance issues.
The way Polymer works around this is it looks at the link
tags and uses xhr
to load those styles and apply them.
edit:
The folks working on Shadow DOM are aware of this shortcoming and that it needs to be fixed. Hopefully in the future we can come up with a system that supports external stylesheets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With