简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM