Skip to content

Commit 3864eb4

Browse files
committed
Change styleSheet loading for shadow root
1 parent eac0289 commit 3864eb4

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

demo-app/components/host-wrapper.gts

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,29 @@ export default class HostWrapper extends Component<{
1515
this.shadow = shadowRoot;
1616
};
1717

18-
get getStyles() {
19-
return [...document.head.querySelectorAll('link')].map((link) => link.href);
20-
}
21-
2218
attachShadow = modifier(
2319
(element: Element, [set]: [(shadowRoot: HTMLDivElement) => void]) => {
24-
let shadowRoot = element;
20+
let shadowRoot: Element | ShadowRoot = element;
2521
if (shadowRootBuild) {
26-
shadowRoot = element.attachShadow({
27-
mode: 'open',
28-
}) as unknown as Element;
22+
const sr = element.attachShadow({ mode: 'open' });
23+
// Apply document stylesheets synchronously via Constructable Stylesheets
24+
// so that layout (offsetHeight, offsetTop) is correct immediately when
25+
// modifiers fire — avoiding the async <link> race condition.
26+
sr.adoptedStyleSheets = [...document.styleSheets].reduce<
27+
CSSStyleSheet[]
28+
>((acc, sheet) => {
29+
try {
30+
const cs = new CSSStyleSheet();
31+
cs.replaceSync(
32+
[...sheet.cssRules].map((r) => r.cssText).join('\n'),
33+
);
34+
acc.push(cs);
35+
} catch {
36+
// Skip cross-origin stylesheets whose rules are inaccessible
37+
}
38+
return acc;
39+
}, []);
40+
shadowRoot = sr;
2941
}
3042
const div = document.createElement('div');
3143
shadowRoot.appendChild(div);
@@ -42,9 +54,6 @@ export default class HostWrapper extends Component<{
4254
{{#if this.shadow}}
4355
{{#in-element this.shadow}}
4456
{{#if shadowRootBuild}}
45-
{{#each this.getStyles as |styleHref|}}
46-
<link rel="stylesheet" type="text/css" href={{styleHref}} />
47-
{{/each}}
4857
<BasicDropdownWormhole />
4958
{{/if}}
5059
{{yield}}

0 commit comments

Comments
 (0)