Skip to content

Commit

Permalink
feat: skip pinging the server when the tab is not shown
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Apr 2, 2023
1 parent fdef8fd commit 62af5bc
Showing 1 changed file with 34 additions and 9 deletions.
43 changes: 34 additions & 9 deletions packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,23 +315,48 @@ async function waitForSuccessfulPing(
) {
const pingHostProtocol = socketProtocol === 'wss' ? 'https' : 'http'

// eslint-disable-next-line no-constant-condition
while (true) {
const ping = async () => {
// A fetch on a websocket URL will return a successful promise with status 400,
// but will reject a networking error.
// When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors
try {
// A fetch on a websocket URL will return a successful promise with status 400,
// but will reject a networking error.
// When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors
await fetch(`${pingHostProtocol}://${hostAndPath}`, {
mode: 'no-cors',
})
break
} catch (e) {
// wait ms before attempting to ping again
await new Promise((resolve) => setTimeout(resolve, ms))
return true
} catch {}
return false
}

// eslint-disable-next-line no-constant-condition
while (true) {
if (document.visibilityState === 'visible') {
if (await ping()) {
break
}
await wait(ms)
} else {
await Promise.race([wait(ms), waitForWindowShow()])
}
}
}

function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}

function waitForWindowShow() {
return new Promise<void>((resolve) => {
const onChange = async () => {
if (document.visibilityState === 'visible') {
resolve()
document.removeEventListener('visibilitychange', onChange)
}
}
document.addEventListener('visibilitychange', onChange)
})
}

const sheetsMap = new Map<string, HTMLStyleElement>()
// all css imports should be inserted at the same position
// because after build it will be a single css file
Expand Down

0 comments on commit 62af5bc

Please sign in to comment.