Unverified Commit ef8fef13 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Fix link not being GC'd sometimes (#49318)

The `app-link-gc` module should treat the link with just pathname as the
href and full URL as the same resource. This avoids duplicate styles
during HMR:

<img width="482" alt="CleanShot 2023-05-05 at 18 12 12@2x"
src="https://user-images.githubusercontent.com/3676859/236511257-af510ed2-8e21-430a-bf71-24931b10e5de.png">

[Related bug report
(internal)](https://vercel.slack.com/archives/C03KAR5DCKC/p1683295788069859).
parent 75eccf7c
...@@ -15,9 +15,22 @@ export function linkGc() { ...@@ -15,9 +15,22 @@ export function linkGc() {
if (href) { if (href) {
const [resource, version] = href.split('?v=') const [resource, version] = href.split('?v=')
if (version) { if (version) {
const allLinks = document.querySelectorAll( const currentOrigin = window.location.origin
`link[href^="${resource}"]` const allLinks = [
) as NodeListOf<HTMLLinkElement> ...document.querySelectorAll(
'link[href^="' + resource + '"]'
),
// It's possible that the resource is a full URL or only pathname,
// so we need to remove the alternative href as well.
...document.querySelectorAll(
'link[href^="' +
(resource.startsWith(currentOrigin)
? resource.slice(currentOrigin.length)
: currentOrigin + resource) +
'"]'
),
] as HTMLLinkElement[]
for (const otherLink of allLinks) { for (const otherLink of allLinks) {
if (otherLink.dataset.precedence?.startsWith('next')) { if (otherLink.dataset.precedence?.startsWith('next')) {
const otherHref = otherLink.getAttribute('href') const otherHref = otherLink.getAttribute('href')
......
...@@ -586,6 +586,35 @@ createNextDescribe( ...@@ -586,6 +586,35 @@ createNextDescribe(
await next.patchFile(filePath, origContent) await next.patchFile(filePath, origContent)
} }
}) })
it('should not create duplicate link tags during HMR', async () => {
const filePath = 'app/hmr/global.css'
const origContent = await next.readFile(filePath)
const browser = await next.browser('/hmr')
try {
await next.patchFile(
filePath,
origContent.replace('background: gray;', 'background: red;')
)
await check(
() =>
browser.eval(
`window.getComputedStyle(document.querySelector('body')).backgroundColor`
),
'rgb(255, 0, 0)'
)
await check(
() =>
browser.eval(
`document.querySelectorAll('link[rel="stylesheet"][href*="/page.css"]').length`
),
1
)
} finally {
await next.patchFile(filePath, origContent)
}
})
} }
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment