Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 642
dtracers Avatar asked Apr 19 '14 22:04

dtracers


2 Answers

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.

like image 71
blackBox solutions Avatar answered Oct 02 '22 01:10

blackBox solutions


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.

like image 20
Himanshu sharma Avatar answered Oct 02 '22 01:10

Himanshu sharma