diff --git a/src/utils/shadow-root.ts b/src/utils/shadow-root.ts index 2de279f2604..c8c69867063 100644 --- a/src/utils/shadow-root.ts +++ b/src/utils/shadow-root.ts @@ -1,9 +1,11 @@ import { BUILD } from '@app-data'; import { globalStyles } from '@app-globals'; -import { supportsConstructableStylesheets } from '@platform'; import { CMP_FLAGS } from '@utils'; import type * as d from '../declarations'; +import { createStyleSheetIfNeededAndSupported } from './style'; + +let globalStyleSheet: CSSStyleSheet | null | undefined; export function createShadowRoot(this: HTMLElement, cmpMeta: d.ComponentRuntimeMeta) { const shadowRoot = BUILD.shadowDelegatesFocus @@ -13,13 +15,9 @@ export function createShadowRoot(this: HTMLElement, cmpMeta: d.ComponentRuntimeM }) : this.attachShadow({ mode: 'open' }); - /** - * If constructable stylesheets are supported, we can use them to - * add the global styles to the shadow root. - */ - if (supportsConstructableStylesheets) { - const sheet = new CSSStyleSheet(); - sheet.replaceSync(globalStyles); - shadowRoot.adoptedStyleSheets.push(sheet); - } + // Initialize if undefined, set to CSSStyleSheet or null + if (globalStyleSheet === undefined) globalStyleSheet = createStyleSheetIfNeededAndSupported(globalStyles) ?? null; + + // Use initialized global stylesheet if available + if (globalStyleSheet) shadowRoot.adoptedStyleSheets.push(globalStyleSheet); } diff --git a/src/utils/style.ts b/src/utils/style.ts new file mode 100644 index 00000000000..7b8e8204358 --- /dev/null +++ b/src/utils/style.ts @@ -0,0 +1,16 @@ +import { supportsConstructableStylesheets } from '@platform'; + +/** + * If (1) styles is not empty string, and (2) constructable stylesheets are supported, + * then make a stylesheet. + * + * @param styles - The styles to add to the stylesheet. If empty string, then no stylesheet is returned. + * @returns A stylesheet if it can be created, otherwise undefined. + */ +export function createStyleSheetIfNeededAndSupported(styles: string): CSSStyleSheet | undefined { + if (!styles || !supportsConstructableStylesheets) return undefined; + + const sheet = new CSSStyleSheet(); + sheet.replaceSync(styles); + return sheet; +}