Skip to content

Commit

Permalink
fix(shadow-wrapper): wait for shadowStyles load before calling `sha…
Browse files Browse the repository at this point in the history
…dowReadyCallback` (#611)

Co-authored-by: nd0ut <[email protected]>
  • Loading branch information
nd0ut and nd0ut authored Feb 20, 2024
1 parent 1dcaf8d commit 42b73b7
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion blocks/ShadowWrapper/ShadowWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,33 @@ export function shadowed(Base) {

shadowReadyCallback() {}

/**
* @private
*
* This is super tricky workaround to wait for shadow styles to load. When `shadowStyles` is defined, symbiote will
* wait for it to load before rendering the component. So the `render` method becomes async. We need to call
* `shadowReadyCallback` right after the rendering is done. But we can't just call it after `render` because it's
* async. So we need to wait for the shadow styles to load and then call `shadowReadyCallback`.
*/
async _waitForShadowStylesLoad() {
if (!this.shadowRoot) {
return;
}
// @ts-expect-error
const shadowStylesUrl = this.constructor['__shadowStylesUrl'];
/** @type {HTMLLinkElement | null} */
const link = this.shadowRoot.querySelector(`link[href="${shadowStylesUrl}"]`);

if (!link) {
return;
}

await new Promise((resolve, reject) => {
link.addEventListener('load', resolve);
link.addEventListener('error', reject);
});
}

initCallback() {
super.initCallback();
this.setAttribute('hidden', '');
Expand All @@ -41,8 +68,9 @@ export function shadowed(Base) {
link.onload = () => {
// CSS modules can be not loaded at this moment
// TODO: investigate better solution
window.requestAnimationFrame(() => {
window.requestAnimationFrame(async () => {
this.render();
await this._waitForShadowStylesLoad();
window.setTimeout(() => {
this.removeAttribute('hidden');
this.shadowReadyCallback();
Expand Down

0 comments on commit 42b73b7

Please sign in to comment.