csshtmlstylesheetshadow-domtemplatetag

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


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.

EX:

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

script to include template:

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

Solution

  • 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 that now I'm having some cache issues as Chrome does not seem to reload those resources after a hard reload.