Skip to content

Commit fe5d130

Browse files
authored
fix(utils): single global stylesheet instance for performance (#6320)
* fix(utils): single global stylesheet instance for performance * lazy getter * simplify
1 parent e35a004 commit fe5d130

File tree

2 files changed

+24
-10
lines changed

2 files changed

+24
-10
lines changed

src/utils/shadow-root.ts

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { BUILD } from '@app-data';
22
import { globalStyles } from '@app-globals';
3-
import { supportsConstructableStylesheets } from '@platform';
43
import { CMP_FLAGS } from '@utils';
54

65
import type * as d from '../declarations';
6+
import { createStyleSheetIfNeededAndSupported } from './style';
7+
8+
let globalStyleSheet: CSSStyleSheet | null | undefined;
79

810
export function createShadowRoot(this: HTMLElement, cmpMeta: d.ComponentRuntimeMeta) {
911
const shadowRoot = BUILD.shadowDelegatesFocus
@@ -13,13 +15,9 @@ export function createShadowRoot(this: HTMLElement, cmpMeta: d.ComponentRuntimeM
1315
})
1416
: this.attachShadow({ mode: 'open' });
1517

16-
/**
17-
* If constructable stylesheets are supported, we can use them to
18-
* add the global styles to the shadow root.
19-
*/
20-
if (supportsConstructableStylesheets) {
21-
const sheet = new CSSStyleSheet();
22-
sheet.replaceSync(globalStyles);
23-
shadowRoot.adoptedStyleSheets.push(sheet);
24-
}
18+
// Initialize if undefined, set to CSSStyleSheet or null
19+
if (globalStyleSheet === undefined) globalStyleSheet = createStyleSheetIfNeededAndSupported(globalStyles) ?? null;
20+
21+
// Use initialized global stylesheet if available
22+
if (globalStyleSheet) shadowRoot.adoptedStyleSheets.push(globalStyleSheet);
2523
}

src/utils/style.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { supportsConstructableStylesheets } from '@platform';
2+
3+
/**
4+
* If (1) styles is not empty string, and (2) constructable stylesheets are supported,
5+
* then make a stylesheet.
6+
*
7+
* @param styles - The styles to add to the stylesheet. If empty string, then no stylesheet is returned.
8+
* @returns A stylesheet if it can be created, otherwise undefined.
9+
*/
10+
export function createStyleSheetIfNeededAndSupported(styles: string): CSSStyleSheet | undefined {
11+
if (!styles || !supportsConstructableStylesheets) return undefined;
12+
13+
const sheet = new CSSStyleSheet();
14+
sheet.replaceSync(styles);
15+
return sheet;
16+
}

0 commit comments

Comments
 (0)