diff --git a/packages/playground/hmr/__tests__/hmr.spec.ts b/packages/playground/hmr/__tests__/hmr.spec.ts index 34612ee1e7d3d5..dfc32109567066 100644 --- a/packages/playground/hmr/__tests__/hmr.spec.ts +++ b/packages/playground/hmr/__tests__/hmr.spec.ts @@ -161,6 +161,20 @@ if (!isBuild) { expect(textpost).not.toMatch('direct') }) + test('it swaps out link tags', async () => { + await page.goto(viteTestUrl) + + editFile('global.css', (code) => code.replace('white', 'tomato')) + + let el = await page.$('.link-tag-added') + await untilUpdated(() => el.textContent(), 'yes') + + el = await page.$('.link-tag-removed') + await untilUpdated(() => el.textContent(), 'yes') + + expect((await page.$$('link')).length).toBe(1) + }) + test('not loaded dynamic import', async () => { await page.goto(viteTestUrl + '/counter/index.html') diff --git a/packages/playground/hmr/hmr.ts b/packages/playground/hmr/hmr.ts index 113b87bc5865d4..f2d21b9bc78884 100644 --- a/packages/playground/hmr/hmr.ts +++ b/packages/playground/hmr/hmr.ts @@ -41,12 +41,42 @@ if (import.meta.hot) { update.type === 'css-update' && update.path.match('global.css') ) if (cssUpdate) { - const el = document.querySelector('#global-css') as HTMLLinkElement - text('.css-prev', el.href) - // We don't have a vite:afterUpdate event, but updates are currently sync - setTimeout(() => { - text('.css-post', el.href) - }, 0) + text( + '.css-prev', + (document.querySelector('.global-css') as HTMLLinkElement).href + ) + + // We don't have a vite:afterUpdate event. + // We need to wait until the tag has been swapped out, which + // includes the time taken to download and parse the new stylesheet. + const observer = new MutationObserver((mutations) => { + mutations.forEach((mutation) => { + mutation.addedNodes.forEach((node) => { + if ( + node.nodeType === Node.ELEMENT_NODE && + (node as Element).tagName === 'LINK' + ) { + text('.link-tag-added', 'yes') + } + }) + mutation.removedNodes.forEach((node) => { + if ( + node.nodeType === Node.ELEMENT_NODE && + (node as Element).tagName === 'LINK' + ) { + text('.link-tag-removed', 'yes') + text( + '.css-post', + (document.querySelector('.global-css') as HTMLLinkElement).href + ) + } + }) + }) + }) + + observer.observe(document.querySelector('#style-tags-wrapper'), { + childList: true + }) } }) diff --git a/packages/playground/hmr/index.html b/packages/playground/hmr/index.html index 65a2ed381b027a..7857ef818a911c 100644 --- a/packages/playground/hmr/index.html +++ b/packages/playground/hmr/index.html @@ -1,4 +1,10 @@ - +
+ +