在模板标签内使用远程样式表(带阴影dom)

dtr*_*ers 15 css html5 stylesheet templatetag shadow-dom

我正在尝试制作一个半可重复使用的小部件,但我遇到了一个问题.我试图在阴影根中封装一些CSS代码,这样它就不会影响网页的其余部分,但是这个CSS用于多个小部件,所以我试图包含一个远程样式表.我找到的所有例子都没有使用远程样式表,我想知道这是否可行.

EX:

<template id="templateContent">
    <head>
        <link rel="stylesheet" href="css/generalStyle1.css">
    </head>
    <body>
        <div class="affectedByGeneralStyle1"></div>
    </body>
</template>
Run Code Online (Sandbox Code Playgroud)

用于包含模板的脚本:

<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>
Run Code Online (Sandbox Code Playgroud)

bla*_*ons 19

我最近遇到了同样的问题,我最终做的是使用:

<template id="templateContent">
     <style> @import "css/generalStyle.css"; </style>
</template>
Run Code Online (Sandbox Code Playgroud)

附加信息:这工作得很好,除了,现在我有一些缓存问题,因为Chrome似乎没有在重新加载后重新加载这些资源.

  • 一些额外的信息:这里是 [相关规范](https://w3c.github.io/webcomponents/spec/shadow/#inert-html-elements) 说 `&lt;link&gt;` 在 shadow DOM 中是惰性的。 (2认同)

Him*_*rma 7

让我们回答一下.现在,阴影dom支持直接标记.

你可以直接使用

<link rel="stylesheet" href="yourcss1.css">
<link href="yourcss2.css" rel="stylesheet" type="text/css">  
Run Code Online (Sandbox Code Playgroud)

检查它们是由whatwg和W3C更新的

在阴影dom中使用css的有用链接.

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

直接css链接可以在阴影dom中使用

谢谢.