Skip to content

Commit

Permalink
Merge pull request #57 from benjaminrobinet/master
Browse files Browse the repository at this point in the history
fix: stylesheet loading
  • Loading branch information
daun authored Nov 14, 2024
2 parents bc2e7cd + 772964c commit 1271d31
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
11 changes: 7 additions & 4 deletions src/mergeHeadContents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,18 @@ export default function mergeHeadContents(
.forEach(({ el }) => currentHead.removeChild(el));

// Insert tag *after* previous version of itself to preserve JS variable scope and CSS cascade
addTags
const newAddTags = addTags
.filter(({ el }) => shouldManageTag(el))
.forEach(({ el, index = 0 }) => {
currentHead.insertBefore(el.cloneNode(true), currentHead.children[index + 1] || null);
.map((tag) => {
let newEl = tag.el.cloneNode(true) as Element;
currentHead.insertBefore(newEl, currentHead.children[(tag.index || 0) + 1] || null);

return { ...tag, el: newEl };
});

return {
removed: removeTags.map(({ el }) => el),
added: addTags.map(({ el }) => el)
added: newAddTags.map(({ el }) => el)
};
}

Expand Down
9 changes: 7 additions & 2 deletions src/waitForAssets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,23 @@ export function waitForStylesheet(
element: HTMLLinkElement,
timeoutMs: number = 0
): Promise<HTMLLinkElement> {
let timeoutId: ReturnType<typeof setTimeout>;

const whenLoaded = (cb: () => void) => {
if (element.sheet) {
cb();
} else {
setTimeout(() => whenLoaded(cb), 10);
timeoutId = setTimeout(() => whenLoaded(cb), 10);
}
};

return new Promise((resolve) => {
whenLoaded(() => resolve(element));
if (timeoutMs > 0) {
setTimeout(() => resolve(element), timeoutMs);
setTimeout(() => {
if (timeoutId) clearTimeout(timeoutId);
resolve(element);
}, timeoutMs);
}
});
}

0 comments on commit 1271d31

Please sign in to comment.