Thinking Sites
Thinking Sites

Reputation: 3542

External stylesheets for shadow dom in web components

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?

Upvotes: 11

Views: 4125

Answers (2)

robdodson
robdodson

Reputation: 6786

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.

Upvotes: 9

Varunkumar Nagarajan
Varunkumar Nagarajan

Reputation: 2055

Shadow DOM doesn't react to link tags. Infact, Chrome 41 throws an error when you use link tags. We have worked around that limitation by inlining CSS classes at the build time using vulcanize. This turned out to be quite handy in separating your CSS and the component definition.

Upvotes: 0

Related Questions