Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: stylesheet loading #57

Merged
merged 3 commits into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
});
}
Loading