/
app-link-gc.ts
53 lines (52 loc) · 2.04 KB
/
app-link-gc.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
export function linkGc() {
// TODO-APP: Remove this logic when Float has GC built-in in development.
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 === 'next.js') {
const href = link.getAttribute('href')
if (href) {
const [resource, version] = href.split('?v=')
if (version) {
const allLinks = document.querySelectorAll(
`link[href^="${resource}"]`
) as NodeListOf<HTMLLinkElement>
for (const otherLink of allLinks) {
if (otherLink.dataset.precedence === 'next.js') {
const otherHref = otherLink.getAttribute('href')
if (otherHref) {
const [, otherVersion] = otherHref.split('?v=')
if (!otherVersion || +otherVersion < +version) {
otherLink.remove()
const preloadLink = document.querySelector(
`link[rel="preload"][as="style"][href="${otherHref}"]`
)
if (preloadLink) {
preloadLink.remove()
}
}
}
}
}
}
}
}
}
}
}
}
}
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback)
observer.observe(document.head, {
childList: true,
})
}
}