Use a remote stylesheet inside a template tag (with shadow dom)

孤者浪人 提交于 2019-12-03 10:42:13

i came across the same problem recently, what i ended up doing was using:

<template id="templateContent">
     <style> @import "css/generalStyle.css"; </style>
</template>

additional info: this worked just fine except, now i'm having some cache issues as Chrome does not seem to reload those ressources after a hard reload.

Let add to the answer . Now direct tag is supported in shadow dom.

You can directly use

<link rel="stylesheet" href="yourcss1.css">
<link href="yourcss2.css" rel="stylesheet" type="text/css">  

Check they has been update by whatwg and W3C

Useful link for using css in shadow dom.

https://w3c.github.io/webcomponents/spec/shadow/#inertness-of-html-elements-in-a-shadow-tree https://github.com/whatwg/html/commit/43c57866c2bbc20dc0deb15a721a28cbaad2140c

https://github.com/w3c/webcomponents/issues/628

Direct css link can be use in shadow dom

Thanks.

actually polymer has an internal utility to load css links, i have implemented a javascript function that is using polymer internal css processor,so if you want to add css links at runtime you can use it:

Polymer('my-element', {           
        ready: function () {
           this.importCss("path/myfile.css");
        },
        importCss: function (path) {
             var $shadow = $(this.shadowRoot);
            var $head = $("<div></div>");
            var $link = $("<link rel='stylesheet' type='text/css'>");
            $link.attr("href", path);
            $head.append($link);
            var head = $head[0];
            this.copySheetAttributes = Polymer.api.declaration.styles.copySheetAttributes;
            Polymer.api.declaration.styles.convertSheetsToStyles.call(this, head);
            var styles = Polymer.api.declaration.styles.findLoadableStyles(head);
            if (styles.length) {
                var templateUrl = this.baseURI;
                Polymer.styleResolver.loadStyles(styles, templateUrl, function () {
                    var $style = $shadow.find("style");
                    if ($style.length > 0){
                        $shadow.find("style").append($head.find("style").html());
                    }else{
                        $shadow.append($head.html());
                    }
                });
            }
        }
});

Note: this code needs jquery to run

I added the stylesheet's link element directly to the shadow root this way:

    let link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.setAttribute('href', 'whatever.css');
    this.shadowRoot.appendChild(link);

It seems to work fine. (I called this from the constructor of the component.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!