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

后端 未结 4 731
生来不讨喜
生来不讨喜 2021-01-01 22:13

I am trying to make a semi-resuseable widget but I am running into a problem. I am trying to encapsulate a some CSS code inside a shadow root so that it does not affect the

4条回答
  •  失恋的感觉
    2021-01-01 22:17

    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 = $("
    "); var $link = $(""); $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

提交回复
热议问题