Skip to content

[CSS Import Once] @import-once, or some syntax for importing a stylesheet only once #6130

@trusktr

Description

@trusktr

Cascade Layers (#4470) does give us the ability to manage duplication caused by files @importing the same shared files: it allows us to place the (duplicate) imports in a high-cascade layer so that duplicates will not override the overrides of files that import the shared code to override the shared values.

(If that's not clear, let me know and I'll make a live example of the unexpected problems it causes.)

Although this will help, it won't actually prevent the duplication.

Adding something like @import-once would solve the duplication problem regardless of cascade layers, but would still be complimentary to cascade layers.

@import-once would do what the name implies: it only does what @import normally does when a fully-qualified URL has not been imported before.

  • On first occurrence of @import-once "/some.css" it behaves just like @import.
  • On every occurrence after that for the same URL (based on it's fully-qualified value), it is effectively skipped (no-op).
    • Maybe it isn't a complete no-op: perhaps all style sheets that import the same style URL with @import-once will have a link to the same CSSStyleSheet in their import-once rule object.
    • The feature is a "no-op" behavior-wise when it comes to the style rules that are actually applied to the DOM.

Only one stylesheet with content from some.css will be loaded. The behavior is based on the fully-resolved URLs, otherwise differing relative paths pointing to the same file would still load, causing duplication.

So it's not completely a no-op after the first occurrence: it still needs to resolve the URL, and it determines whether to continue or not based on the fully-qualified URL.

Sidenote, CSS ES Modules will behave like @import-once. They also talked about making @import in CSS Modules behave like the @import-once idea here for various reasons (but that would be a hack, better to let the CSS work as expected, and give CSS @import-once in addition).


Also see the @import (once) syntax from Less. It is the default behavior for @import in Less.

@import-once syntax is bike-sheddable.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions