diff --git a/src/mergeHeadContents.ts b/src/mergeHeadContents.ts index aad2f6a..fc56afb 100644 --- a/src/mergeHeadContents.ts +++ b/src/mergeHeadContents.ts @@ -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) }; } diff --git a/src/waitForAssets.ts b/src/waitForAssets.ts index cd1c6d0..db230f6 100644 --- a/src/waitForAssets.ts +++ b/src/waitForAssets.ts @@ -13,18 +13,23 @@ export function waitForStylesheet( element: HTMLLinkElement, timeoutMs: number = 0 ): Promise { + let timeoutId: ReturnType; + 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); } }); }