Skip to content

Commit bc6995e

Browse files
committed
fix(css): avoid duplicate style for server rendered stylesheet link
1 parent cc54e29 commit bc6995e

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

packages/vite/src/client/client.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,7 @@ async function waitForSuccessfulPingInternal(
495495
}
496496

497497
const sheetsMap = new Map<string, HTMLStyleElement>()
498+
const linkSheetsMap = new Map<string, HTMLLinkElement>()
498499

499500
// collect existing style elements that may have been inserted during SSR
500501
// to avoid FOUC or duplicate styles
@@ -504,6 +505,13 @@ if ('document' in globalThis) {
504505
.forEach((el) => {
505506
sheetsMap.set(el.getAttribute('data-vite-dev-id')!, el)
506507
})
508+
document
509+
.querySelectorAll<HTMLLinkElement>(
510+
'link[rel="stylesheet"][data-vite-dev-id]',
511+
)
512+
.forEach((el) => {
513+
linkSheetsMap.set(el.getAttribute('data-vite-dev-id')!, el)
514+
})
507515
}
508516

509517
const cspNonce =
@@ -516,6 +524,8 @@ const cspNonce =
516524
let lastInsertedStyle: HTMLStyleElement | undefined
517525

518526
export function updateStyle(id: string, content: string): void {
527+
if (linkSheetsMap.has(id)) return
528+
519529
let style = sheetsMap.get(id)
520530
if (!style) {
521531
style = document.createElement('style')
@@ -545,6 +555,11 @@ export function updateStyle(id: string, content: string): void {
545555
}
546556

547557
export function removeStyle(id: string): void {
558+
const link = linkSheetsMap.get(id)
559+
if (link) {
560+
document.head.removeChild(link)
561+
linkSheetsMap.delete(id)
562+
}
548563
const style = sheetsMap.get(id)
549564
if (style) {
550565
document.head.removeChild(style)

0 commit comments

Comments
 (0)