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

为君一笑 提交于 2020-02-26 12:02:27


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 rest of the webpage but this CSS is used across multiple widgets so I am trying to include a remote stylesheet. None of the examples I have found use a remote style sheet and I was wondering if this was possible.


<template id="templateContent">
        <link rel="stylesheet" href="css/generalStyle1.css">
        <div class="affectedByGeneralStyle1"></div>

script to include template:

<div id="host"></div>
    var importedData = (html_import_element).import.getElementById("templateContent");
    var shadow = document.querySelector('#host').createShadowRoot();
    var clone = document.importNode(importedData.content, true);


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

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

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.

Direct css link can be use in shadow dom



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 () {
        importCss: function (path) {
             var $shadow = $(this.shadowRoot);
            var $head = $("<div></div>");
            var $link = $("<link rel='stylesheet' type='text/css'>");
            $link.attr("href", path);
            var head = $head[0];
            this.copySheetAttributes = Polymer.api.declaration.styles.copySheetAttributes;
  , 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){

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');

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