Skip to content

Commit bedcd8f

Browse files
authored
feat: skip pinging the server when the tab is not shown (#12698)
1 parent 2d30ae5 commit bedcd8f

File tree

1 file changed

+39
-9
lines changed

1 file changed

+39
-9
lines changed

packages/vite/src/client/client.ts

+39-9
Original file line numberDiff line numberDiff line change
@@ -315,23 +315,53 @@ async function waitForSuccessfulPing(
315315
) {
316316
const pingHostProtocol = socketProtocol === 'wss' ? 'https' : 'http'
317317

318-
// eslint-disable-next-line no-constant-condition
319-
while (true) {
318+
const ping = async () => {
319+
// A fetch on a websocket URL will return a successful promise with status 400,
320+
// but will reject a networking error.
321+
// When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors
320322
try {
321-
// A fetch on a websocket URL will return a successful promise with status 400,
322-
// but will reject a networking error.
323-
// When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors
324323
await fetch(`${pingHostProtocol}://${hostAndPath}`, {
325324
mode: 'no-cors',
326325
})
327-
break
328-
} catch (e) {
329-
// wait ms before attempting to ping again
330-
await new Promise((resolve) => setTimeout(resolve, ms))
326+
return true
327+
} catch {}
328+
return false
329+
}
330+
331+
if (await ping()) {
332+
return
333+
}
334+
await wait(ms)
335+
336+
// eslint-disable-next-line no-constant-condition
337+
while (true) {
338+
if (document.visibilityState === 'visible') {
339+
if (await ping()) {
340+
break
341+
}
342+
await wait(ms)
343+
} else {
344+
await waitForWindowShow()
331345
}
332346
}
333347
}
334348

349+
function wait(ms: number) {
350+
return new Promise((resolve) => setTimeout(resolve, ms))
351+
}
352+
353+
function waitForWindowShow() {
354+
return new Promise<void>((resolve) => {
355+
const onChange = async () => {
356+
if (document.visibilityState === 'visible') {
357+
resolve()
358+
document.removeEventListener('visibilitychange', onChange)
359+
}
360+
}
361+
document.addEventListener('visibilitychange', onChange)
362+
})
363+
}
364+
335365
const sheetsMap = new Map<string, HTMLStyleElement>()
336366
// all css imports should be inserted at the same position
337367
// because after build it will be a single css file

0 commit comments

Comments
 (0)