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(hmr): duplicate link tags #9697

Merged
merged 2 commits into from Aug 16, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 10 additions & 2 deletions packages/vite/src/client/client.ts
Expand Up @@ -126,6 +126,7 @@ function cleanUrl(pathname: string): string {
}

let isFirstUpdate = true
const invalidLinkTags = new Set<HTMLLinkElement>()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we could use WeakSet to be safe?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm..., I'm not sure about the client code's browser support

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are transpiling client code to es2019. So I believe it's fine.

sapphi-red marked this conversation as resolved.
Show resolved Hide resolved

async function handleMessage(payload: HMRPayload) {
switch (payload.type) {
Expand Down Expand Up @@ -166,7 +167,10 @@ async function handleMessage(payload: HMRPayload) {
// URL for the include check.
const el = Array.from(
document.querySelectorAll<HTMLLinkElement>('link')
).find((e) => cleanUrl(e.href).includes(searchUrl))
).find(
(e) =>
!invalidLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl)
)
if (el) {
const newPath = `${base}${searchUrl.slice(1)}${
searchUrl.includes('?') ? '&' : '?'
Expand All @@ -179,9 +183,13 @@ async function handleMessage(payload: HMRPayload) {
// directly, as the new stylesheet has not yet been loaded.
const newLinkTag = el.cloneNode() as HTMLLinkElement
newLinkTag.href = new URL(newPath, el.href).href
const removeOldEl = () => el.remove()
const removeOldEl = () => {
el.remove()
invalidLinkTags.delete(el)
}
newLinkTag.addEventListener('load', removeOldEl)
newLinkTag.addEventListener('error', removeOldEl)
invalidLinkTags.add(el)
el.after(newLinkTag)
}
console.log(`[vite] css hot updated: ${searchUrl}`)
Expand Down