Skip to content

Declarative CSS Module Scripts #939

Open

Description

@justinfagnani

Declarative shadow roots and constructible stylesheets need to be made to work together so that stylesheets added to shadow roots can be round-tripped through HTML serialization and deserialization.

As of now, SSR code will have to read a shadow root's adopted stylesheets and write them to HTML as <style> tags. While this will style they shadow roots correctly on first render, it results in bloated a HTML payload and breaks the shared stylehseet semantics. Hydration code would have to deduplicate <style> tags and create and attach constructed stylesheets in order to reconstruct the origin DOM structure.

To solve this we need a serialized form of constructible stylesheets. These are stylesheets that do not automatically apply to any scope, but can be associated and applied by reference.

Requirements:

  1. Ability to serialize a constructed stylesheet to HTML (edit to clarify: on the server)
  2. Styles don't automatically apply to the document or any shadow root
  3. Styles are able to be associated with declarative shadow root instances (edit to clarify: which populate the shadow root's adoptedStyleSheets)
  4. To support streaming SSR, the styles must be able to be written with the first scope that uses it and referenced in later scopes.

One idea is to add a new type for <style> tags that accepts CSS text and creates a new constructed stylesheet:

  <style type="adopted-css" id="style-one">
    :host {
      color: red
    }
  </style>

This style can then be associated with a declarative shadow root:

  <my-element>
    <template shadowroot="open" adopted-styles="style-one">
      <!-- ... -->
    </template>
  </my-element>

Having a type other than text/css means that the styles won't apply to the document scope even in older browsers. It's also what allows it to have an adoptable CSSStyleSheet .sheet, which replace() works on as well.

One problem that immediately come up is scopes and idrefs. If a declarative stylesheet is only addressable from within a single scope, it's no better than a plain <style> tag because it would have to be duplicated in every scope that uses it. We need some sort of cross-scope idref mechanism. With that we can write the styles with the first scope that uses them, and reference them in later scopes in the document:

  <my-element>
    <template shadowroot="open" adopted-styles="x61h8cys">
      <style type="adopted-css" xid="x61h8cys">
        :host {
          color: red
         }
      </style>
      <!-- ... -->
    </template>
  </my-element>
  <my-element>
    <template shadowroot="open" adopted-styles="x61h8cys">
      <!-- ... -->
    </template>
  </my-element>

Here xid is a stand-in for some kind of cross-scope ID. "x61h8cys" is a stand-in for a GUID or other globally unique value (such as a hash of the style text) that the SSR code would be responsible for generating.

There are other instances where we need cross-scope references, like ARIA and label/input associations. I'm not sure if these cases are similar enough to use the same mechanism or not.

Activity

  1. bkardell commented on Aug 16, 2021

    @bkardell

    @justinfagnani is your xid conceptually a DOMTokenList or something similar -- that is, can you import 2? This feels related to at least some of the discussions in #909 - this "idea" at least would at least probably provide a way to achieve use cases for things like those which aren't even 'secret' as much as they are 'shorthand for well-known constructs' like an element that allows markdown, asciimath, or LaTeX and it similar to the thing I created and have used for my own takes on this..

  2. justinfagnani commented on Aug 16, 2021

    @justinfagnani
    ContributorAuthor

    Yes, shadow roots need to be able to reference multiple style sheets.

    I don't personally see this as that much related to #909 ("open-styleable" shadow roots). Rather than allowing anything from the outside to reach into a shadow root, this is just attempting to replicate JS references to these objects in HTML. it shouldn't be loosening encapsulation at all.

  3. justinfagnani commented on Aug 18, 2021

    @justinfagnani
    ContributorAuthor

    Another option instead of - or maybe in addition to - cross-scope refs is to allow inlining of all module types, keying them by URL that adds them to the module cache as if they had been imported. This would allow a page to render with the necessary CSS modules, attach them to the correct scopes, and later to load JS modules that import them without double-loading them.

    <script> tags with type values that match import assertion types would support a new attribute that gives the specifier/URL. Something like:

    <script type="css" specifier="/foo.css">
      :host {
        color: red
       }
    </script>

    A later import: import styles from '/foo.css' assert {type: 'css'} would load the CSS module script defined by the tag.

    Full example:

      <my-element>
        <template shadowroot="open" css-modules="/foo.css /bar.css">
          <script type="css" specifier="/foo.css">
            :host {
              color: red
             }
          </script>
          <!-- ... -->
        </template>
      </my-element>
      <my-element>
        <template shadowroot="open" css-modules="/foo.css /bar.css">
          <!-- ... -->
        </template>
      </my-element>

    This would have to be made coherent with import maps, but it would allow a page to be rendered with correct scoped styles w/o FOUC and w/o duplication of CSS text.

  4. Westbrook commented on Dec 30, 2021

    @Westbrook
    Collaborator

    Being <template shadowroot="open"> creates a shadow root that ID resolution from above does not have access to, should the "expected" version of:

      <my-element>
        <template shadowroot="open" adopted-styles="x61h8cys">
          <style type="adopted-css" xid="x61h8cys">
            :host {
              color: red
             }
          </style>
          <!-- ... -->
        </template>
      </my-element>
    

    Actually be:

      <style type="adopted-css" id="x61h8cys">
        :host {
          color: red
         }
      </style>
      <my-element>
        <template shadowroot="open" adopted-styles="x61h8cys">
          <!-- ... -->
        </template>
      </my-element>
    

    In this wa x61h8cys can be made available for other shadow roots without having to penetrate otherwise encapsulated DOM structures? Or do you think that all style[type="adopted-css"] would be made available globally by default?

    How would you make these "declarative CSS modules" available in an imperative context? Should there be API to allow for resolution of the actual Stylesheet object from the x61h8cys identifier so that it can be adopted by shadow roots deeper within the DOM hierarchy or that might not be delivered declaratively?

    Inversely, should stylesheets that are registered imperatively have API added by which to associate an ID (a la adopted-styles="x61h8cys") so that they could be leveraged in declarative code?

  5. Westbrook commented on Dec 30, 2021

    @Westbrook
    Collaborator

    The example of

    <script type="css" specifier="/foo.css">
      :host {
        color: red
       }
    </script>
    

    Seems like a large change for developers, would it make a shorter step from historic practices to apply this concept via <style> or <link>? E.G:

    <style type="module" src="/foo.css">
      :host {
        color: red
       }
    </style>
    

    OR

    <link rel="stylesheet-module" href="/foo.css" />
    

    In this way we could leverage already existing blocking mechanisms while informing the browser not to apply these styles until adopted. It's possible that link[rel="stylesheet-module"] might fit right into the rel="modulepreload" cache once assert { type: 'css' } hit browsers allowing it to leverage even more pre-existing features.

    Question that applies to both of these approaches, do you expect that values applied to adopted-styles or css-modules would resolve lazily? E.G. could I list these style in my declarative shadow DOM but then load those sheets in a non-blocking way and still have them apply to the shadow root?

  6. bicknellr commented on Jan 28, 2022

    @bicknellr

    +1, I think the idea of using an attribute to provide a URL / specifier is a really interesting thing to explore because it seems like it would generalize well to basically anything in HTML that describes some other resource and has either inline and external forms. (I'm writing it here as cacheas since I don't think it would really be a specifier anymore? Anyway, the name would need bikeshedding.)

    So, not only could you have:

    <script type="module" cacheas="./some-path">
    export let aString = "Hello, World!"
    </script>
    <script type="module">
    import {aString} from "./some-path";
    console.log(aString);
    </script>

    and

    <style cacheas="./some-path">
    body::before {
      content: 'Hello, World!';
    }
    </style>
    <link rel="stylesheet" href="./some-path">

    But also things like:

    <img cacheas="./some-path" src='data:image/svg+xml,<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="120" height="60"><text y="30" x="30">Hello, World!</text></svg>'>
    <img src="./some-path">
  7. justinfagnani commented on Jan 28, 2022

    @justinfagnani
    ContributorAuthor

    @mfreed7 if we wanted this to be a more general feature, should we move the issue to HTML?

  8. calebdwilliams commented on Jul 14, 2022

    @calebdwilliams

    Am I reading right that this idea is a form of declarative module blocks? A bit off-topic, but I'm wondering how that could play with import assertions and this concept, seems like a lot of the semantics are the same … 

  9. rniwa commented on Oct 6, 2022

    @rniwa
    Collaborator

    Yeah, URL based namespacing is exactly like JS modules. In theory, you should be able to define an inline (e.g. data URI) style inside import maps. So the only additional mechanism needed here is the ability to adopt it.

    How about <style type="module" src="foo"></style>.

  10. matthewp commented on Jan 17, 2023

    @matthewp

    @rniwa Would that <style> be resolved synchronously? I just see the word "module" and think async, but this needs to be sync to avoid FOUC.


    cc @mfreed7, @justinfagnani what do you think of the idea @rniwa is proposing here?

  11. sashafirsov commented on Jan 19, 2023

    @sashafirsov

    @justinfagnani , why to limit the adopted-styles concept to the CSS only?
    It is a "library" concept with common scope as in CSS as in custom components registry and perhaps some other common things like import maps.

    I.e. this proposal has to be converted to something like "custom elements library scope".

    If agree, the name adopted-styles does not reflect the semantic meaning.

  12. justinfagnani commented on Jan 23, 2023

    @justinfagnani
    ContributorAuthor

    @matthewp @rniwa that seems good to me.

    My main ask is for a way to emit a style module at the first use site when streaming server rendering a large tree of components, so that further components can use that same style sheet.

    This is needed because some modern streaming SSR approaches do not know what components will be rendered ahead of time, due to request-specific data and data-dependent templating.

    My other thought is whether this is a thing that should apply to all types of module scripts - where an inline tag can contain content, but populate the module cache.

  13. nolanlawson commented on Apr 17, 2023

    @nolanlawson

    I would prefer a syntax on the <template shadowroot> rather than a <style> inside the template. The issue for us (LWC) is that we use adopted stylesheets for pure client-side rendering (for perf reasons), whereas for SSR, since there is no equivalent, we emit an inline <style> which has to be specially handled on the client.

    The main perf benefit of adopted stylesheets that I've seen in my testing is just bypassing the DOM and avoiding the cost of creating/inserting a <style> element (since browsers have optimizations for <style>s inside shadow roots). So if we need to insert a <style> element to match SSR, then I predict the perf benefits of adopted stylesheets would go away, and you may as well use an old-school inline <style>.

  14. nolanlawson commented on Apr 17, 2023

    @nolanlawson

    Update: after discussion, #939 (comment) seems good to me. In SSG (non-streaming) at least, you can hoist the first <script> up into the <head> or something, which resolves the issue with the asymmetry between client-rendered versus server-rendered DOM structure.

  15. 6 remaining items

  16. mayank99 commented on Jun 27, 2024

    @mayank99

    @EisenbergEffect I appreciate your comment, but most of these things should be covered by <link rel="stylesheet"> and @sheet (which can be used together with fragment URLs, according to this resolution), and some of the points feel subjective and abstract. Today, <link rel="stylesheet"> is already a performant way to handle styling in DSD, which is why I'm asking specifically what this proposal adds on top of it.

    You mentioned modules, but this proposal doesn't really address that (hence the name "CSS module scripts"). True CSS modules would need to be usable within CSS itself, even before HTML or JS is involved. I'd imagine that CSS modules would allow a @sheet to be @imported into another CSS file and applied there.

    It's also worth pointing out that DSD still requires repetition of the shadow markup today. When we get HTML modules (and/or DCE), it would reduce this markup repetition. Since <style>/<link> is just markup, HTML modules basically solve this problem of repeated styles. This is also why I think it makes more sense to pursue HTML modules first.

    Lastly, I want to highlight w3c/csswg-drafts#10013, which was recently greenlit. It may sound unrelated, but in my mind it opens up the potential for these two syntaxes to refer to the exact same stylesheet instance:

    <link rel="stylesheet" href="design-system.css#button">
    import buttonStyles from "design-system.css#button" with { type: "css" };
  17. justinfagnani commented on Jun 27, 2024

    @justinfagnani
    ContributorAuthor

    The main purpose of this propose is the same as declarative shadow DOM: to be able to accurately serialize a valid DOM tree to HTML.

    Right now there's no way to properly serialize adoptedStyleSheets. During SSR you can convert them to <style> tags, but you can't deduplicate them, so you end up with potentially hundreds or thousands of duplicate stylesheets. Converting the to <link> tags would likewise result in potentially hundreds of HTTP requests. Both of those workarounds break the semantics of constructible stylesheets.

  18. mayank99 commented on Jun 27, 2024

    @mayank99

    The <style> and <link> tags may be duplicated in the HTML, but they will be optimized by all browsers to point to a single stylesheet instance (similar to adopting a constructed stylesheet). And the HTML size is usually not an issue because it compresses well (and will be completely deduplicated with HTML modules).

  19. justinfagnani commented on Jun 27, 2024

    @justinfagnani
    ContributorAuthor

    It's still non-optimal and breaks semantics. Constructible stylesheets actually share a single stylesheet instance, something that doesn't happen with <style> or <link>.

    There is still a performance hit from so many <style> tags even with deduplication - this was part of the motivation for constructible stylesheets in the first place. The HTML parser still has to consume the bytes of each tag and check the cache. There's still an extra element in the tree. And compression doesn't completely make up for the extra bytes.

    <link> tags would be pretty cumbersome to implement in an SSR system because you have to invent a URL scheme for them. It would be ok with CSS modules, but won't work well for constructible stylesheets created from inline CSS.

  20. Westbrook commented on Jun 28, 2024

    @Westbrook
    Collaborator

    Lastly, I want to highlight w3c/csswg-drafts#10013, which was recently greenlit. It may sound unrelated, but in my mind it opens up the potential for these two syntaxes to refer to the exact same stylesheet instance:

    <link rel="stylesheet" href="design-system.css#button">
    
    import buttonStyles from "design-system.css#button" with { type: "css" };

    @mayank99 has there explicitly been discussion to date that implied that files included via rel="stylesheet" will make it onto the module graph so that they are not requested multiple times. I'd love to join that conversation! The way that opens an alternate version of the above where in a file full of @sheet fragments could be included via rel="stylesheet":

    <link rel="stylesheet" href="design-system.css">

    While being added to the module graph so that extended usage of the same in JS would essentially be modulepreloaded for use like:

    import { button as buttonStyles } from "design-system.css" with { type: "css" };
    import element from '/my-element.css' with { type: 'css' };
    
    class El extends HTMLElement {
      constructor() {
        super();
        this.attachShadow({mode: 'open'});
        this.shadowRoot.adoptedStyleSheets = [buttonStyles, elementStyles];
      }
    }

    Would be awesome!

    Passing that same theoretical approach to developers using DSD would be important to ensure that they can share learned concepts between the HTML-first or JS-first implementations of a shadow root.

    <my-element>
      <template shadowrootmode="open" adoped-style-sheets="/design-system.css#button /my-element.css">
        <!-- ... -->
      </template>
    </my-element>

    Expanding this to include inline <style> elements completes the picture, no matter how you prefer to write you application:

    <link rel="stylesheet" href="design-system.css">
    
    <style type="module" href="/my-element.css">
       // styles
    </style>
    
    <my-element>
      <template shadowrootmode="open" adoped-style-sheets="/design-system.css#button /my-element.css">
        <!-- ... -->
      </template>
    </my-element>
    
    <script type="module">
      import { button as buttonStyles } from "design-system.css" with { type: "css" };
      import element from '/my-element.css' with { type: 'css' };
    
      class El extends HTMLElement {
        constructor() {
          super();
          this.attachShadow({mode: 'open'});
          this.shadowRoot.adoptedStyleSheets = [buttonStyles, elementStyles];
        }
      }
    </script>

    😍

    Editors note: APIs and attribute name FPO only!

  21. mayank99 commented on Jun 28, 2024

    @mayank99

    has there explicitly been discussion to date that implied that files included via rel="stylesheet" will make it onto the module graph so that they are not requested multiple times.

    @Westbrook Not yet, but that's one of the things I'm hoping will be discussed in CSSWG when we talk about adoptable non-constructed stylesheets and @sheet and such. I think these discussions need to happen in parallel with (if not before) declarative adopted stylesheets.

  22. Westbrook commented on Oct 1, 2024

    @Westbrook
    Collaborator
  23. robglidden commented on Oct 3, 2024

    @robglidden

    @KurtCattiSchmidt, @dandclark, and Tien Mai have provided an excellent analysis/proposal loosely titled "Declarative shadow DOM style sharing".

    Framed as "a starting point for engaging the community and standards bodies in developing collaborative solutions fit for standardization", as I understand it, in my words it envisions:

    • a declarative form of ES module imports/exports
    • for importing resources (CSS, HTML & other)
    • into a declarative shadow DOM
    • via the module graph

    Many thanks for potentially moving forward multiple issues like #909, #910, #939, #10176 and more.

    I have made some suggestions in this slide deck with examples on github.

  24. aluhrs13 commented on Jan 17, 2025

    @aluhrs13

    Hi all! I wanted to give an update on Edge's investigation into this space. Based on some of the feedback with our declarative CSS modules proposals we're looking at an @sheet CSS rule as an alternative path for the primary scenarios. There's still a lot of conversations to have and reconciling all the scenarios, but I wanted to share the initial explainer for feedback - https://github.com/MicrosoftEdge/MSEdgeExplainers/blob/main/AtSheet/explainer.md

    To not derail this thread too far from declarative CSS modules, CSSWG issue is probably the right place to post general questions about the new explainer - w3c/csswg-drafts#11509

  25. justinfagnani commented on Jan 17, 2025

    @justinfagnani
    ContributorAuthor

    Based on some of the feedback with our declarative CSS modules proposals we're looking at an @sheet CSS rule as an alternative path for the primary scenarios.

    Sorry, can you explain more how you see the declarative module scripts and multiple-sheets per file solve the same problems? As the initial proposer for these two I see them as basically covering completely different problems.

    • Declarative module scripts is a way to reuse inline CSS modules by reference in HTML.
    • Multiple stylesheets per file is a way to bundle together small stylesheets that should apply individually.

    I don't see how multiple stylesheets per file customer the declarative module scripts use cases at all. We still need a way to emit inline styles into HTML as they're encountered while SSR'ing the component tree, and reference them from other use sites.

  26. jyasskin commented on Jan 18, 2025

    @jyasskin
    Member

    Apologies @justinfagnani if I've missed your point, but the example at https://github.com/MicrosoftEdge/MSEdgeExplainers/blob/main/AtSheet/explainer.md#importing-a-base-set-of-inline-styles-into-a-declarative-shadow-dom seems to demonstrate how to "emit inline styles into HTML as they're encountered while SSR'ing the component tree, and reference them from other use sites.", aside from a nit about exactly how to reference them. Specifically, when the SSR discovers that it's going to need a new style block named 'foo' in a piece of declarative shadow dom, it emits

    <style>
    @sheet foo {
      div {
        color: red;
      }
    }
    </style>
    <template shadowrootmode="open" adoped-style-sheets="foo">
      <span>I'm in the shadow DOM</span>
    </template>

    (If you need to emit the style inside the DSD, it seems like it would also work to use <link rel=stylesheet someNewAttribute=foo>.)

    Open Issue #5 is important here: SSR is going to want to be able to do a structure like:

    <template shadowrootmode="open">
      <!-- Component 1 stuff ...-->
      <!-- Oh, here comes a component that needs some shared style. -->
      <style>@sheet shared-component-style { ... }</style>
      <template shadowrootmode="open" adopted-style-sheets="foo">
        <!-- Shared component shadow DOM -->
      </template>
    </template>
    <!-- Here comes another copy of the component that needs shared style. -->
    <!-- DON'T re-emit the style -->
    <template shadowrootmode="open" adopted-style-sheets="foo inside the above shadow DOM">
      <!-- Shared component shadow DOM -->
    </template>

    That second reference to foo needs to be able to navigate to the @sheet in shadow DOM. It probably doesn't need to use the exact same syntax, but it needs to be able to name it somehow.

  27. nolanlawson commented on Jan 18, 2025

    @nolanlawson

    I think Open Issue #5 is the key point here. When rendering DSD from the server, from a streaming HTML perspective, it would be useful to be able to emit stylesheets as they are "discovered" – regardless of whether that's in light DOM or shadow DOM. (And there would likely be several layers of shadow DOM.)

    FWIW we have a proposal for LWC to solve this style duplication issue, and it relies on being able to dynamically discover, render, and reference stylesheets without needing an external <link>. (This is kind of key, as it would introduce additional complexity to suddenly have a separate subresource to manage.)

    <!-- Oh, here comes a component that needs some shared style. -->

    Slight wrinkle: component #1 may not even "know" that its stylesheet needs to be shared until component #2 comes along. Proactively setting up the first unique instance of a stylesheet for sharing is probably how most web component frameworks are going to want to do this.

  28. justinfagnani commented on May 13, 2025

    @justinfagnani
    ContributorAuthor

    I've been trying to communicate more clearly that this feature should not be tied to DOM structure or shadow root scopes, because what we're attempting to do is serialize JS references, so I made this live example showing the type of client-side structure that we need to SSR, and how shared styles do not conform to any particular DOM layout:

    https://stackblitz.com/edit/declarative-shared-css-stylesheets-example?file=index.html

    I think the main point is that we have JS lines like this:

    import sharedStyles from '../styles/shared-styles.css' with {type: 'css'};
    
    const styles = new CSSStyleSheet();
    
    // In a custom element:
    this.shadowRoot.adoptedStyleSheets = [sharedStyles, styles];

    And we need to serialize that shadow root with those styles, and any other shadow roots that use those styles too. Since JS references can flow to just about anywhere in the app, there is no relationship between them and the structure of nested shadow roots. And since shadow roots directly reference these stylesheets client-side, it is not an encapsulation violation to let them reference them in HTML.

    I think the big mental challenge here seems to be that serializing JavaScript references is inherently less strict than the references behave in JS. In JS we cannot forge a reference to an arbitrary object. Once you have a serialization format, you possibly can. SSR systems could use GUIDs or content digests to make unguessable references, but it's difficult to require and validate that they did so. I also think that this is fine. We aren't allowing arbitrary JS references to be serialized, just those to StyleSheet objects.

  29. justinfagnani commented on May 15, 2025

    @justinfagnani
    ContributorAuthor

    I see that whatwg/html#11019 seems to be making progress, and was discussed some more today, but since that issue doesn't solve for our use cases for sharing styles among declarative shadow roots, is there anyone here in the standards groups that could help move this issue along too?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions