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

feat: skip pinging the server when the tab is not shown #12698

Merged
Merged
Changes from 4 commits
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
47 changes: 38 additions & 9 deletions packages/vite/src/client/client.ts
Expand Up @@ -315,23 +315,52 @@ 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
}

sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
if (await ping()) {
return
}
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved

sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
// eslint-disable-next-line no-constant-condition
while (true) {
if (document.visibilityState === 'visible') {
if (await ping()) {
break
}
await wait(ms)
} else {
await 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