|
|
export function linkGc() { |
|
|
|
|
|
if (process.env.NODE_ENV !== 'production') { |
|
|
const callback = (mutationList: MutationRecord[]) => { |
|
|
for (const mutation of mutationList) { |
|
|
if (mutation.type === 'childList') { |
|
|
for (const node of mutation.addedNodes) { |
|
|
if ( |
|
|
'tagName' in node && |
|
|
(node as HTMLLinkElement).tagName === 'LINK' |
|
|
) { |
|
|
const link = node as HTMLLinkElement |
|
|
if (link.dataset.precedence?.startsWith('next')) { |
|
|
const href = link.getAttribute('href') |
|
|
if (href) { |
|
|
const [resource, version] = href.split('?v=', 2) |
|
|
if (version) { |
|
|
const currentOrigin = window.location.origin |
|
|
const allLinks = [ |
|
|
...document.querySelectorAll( |
|
|
'link[href^="' + resource + '"]' |
|
|
), |
|
|
|
|
|
|
|
|
...document.querySelectorAll( |
|
|
'link[href^="' + |
|
|
(resource.startsWith(currentOrigin) |
|
|
? resource.slice(currentOrigin.length) |
|
|
: currentOrigin + resource) + |
|
|
'"]' |
|
|
), |
|
|
] as HTMLLinkElement[] |
|
|
|
|
|
for (const otherLink of allLinks) { |
|
|
if (otherLink.dataset.precedence?.startsWith('next')) { |
|
|
const otherHref = otherLink.getAttribute('href') |
|
|
if (otherHref) { |
|
|
const [, otherVersion] = otherHref.split('?v=', 2) |
|
|
if (!otherVersion || +otherVersion < +version) { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
setTimeout(() => { |
|
|
otherLink.remove() |
|
|
}, 5) |
|
|
const preloadLink = document.querySelector( |
|
|
`link[rel="preload"][as="style"][href="${otherHref}"]` |
|
|
) |
|
|
if (preloadLink) { |
|
|
preloadLink.remove() |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
const observer = new MutationObserver(callback) |
|
|
observer.observe(document.head, { |
|
|
childList: true, |
|
|
}) |
|
|
} |
|
|
} |
|
|
|