6

Consider, I have few elements which use Shadow DOM to hide their internal div-soup and layout.

Even tough they are different, they share the same CSS style sheet, as they are using the same set of elements that are supposed to be styled in consistent manner. This could be, for example, a CSS framework (bootstrap).

The problem is that this style sheet is pretty big.

What is the most efficient way to share such big style sheet between many Shadow Roots (in SD V1)?

tomalec
  • 890
  • 10
  • 27

1 Answers1

8

UPDATE: 2019 - Use Constructable stylesheets

As of 2019, Constructable stylesheets is the approach to apply stylesheets to shadow DOM and web components in general. Read more about it here.

Previous answer:

You can use an import CSS rule at the first line of a <style> element defined in the Shadow DOM:

<div id=D1></div>
<template id=T1>
   <style>
      @import url( '/css/stylesheet.css' )
   </style>
   ...
</template>

Then import the <template> content in the Shadow DOM root:

var root = D1.attachShadow( {mode: open } )
root.appendChild( T1.content.cloneNode( true ) )
Harshal Patil
  • 17,838
  • 14
  • 60
  • 126
Supersharp
  • 29,002
  • 9
  • 92
  • 134
  • 1
    Thanks! I've created jsbin with your solution http://jsbin.com/veruki/edit?html,output – tomalec Dec 05 '16 at 23:51
  • 2
    What about when we have a ` – trusktr Dec 12 '16 at 00:14
  • @trusktr I suppose I would clone the style element to inject it in the template or directly in the Shadow DOM. – Supersharp Dec 12 '16 at 21:42
  • I've been wanting an elegant solution for this concept [since 2005](https://lists.w3.org/Archives/Public/www-html/2005Jul/0043.html). This is the best answer I've found so far. – Lonnie Best Nov 13 '18 at 06:32
  • 3
    @LonnieBest now you can also use inside Shadow DOM. – Supersharp Nov 13 '18 at 11:41
  • @Supersharp : That's great. I'm glad you mentioned that. – Lonnie Best Nov 15 '18 at 01:04
  • As of Dec 2021, it's still a Chrome-only feature, with Firefox hesitating to roll it out and hiding it behind `about:config > layout.css.constructable-stylesheets.enabled`. Even [caniuse.com](https://caniuse.com/?search=constructable%20stylesheets) is not aware of it ATM. Meanwhile, `` works in both in addition to `` – sunny moon Dec 20 '21 at 21:40