@@ -315,23 +315,53 @@ async function waitForSuccessfulPing(
315
315
) {
316
316
const pingHostProtocol = socketProtocol === 'wss' ? 'https' : 'http'
317
317
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
320
322
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
324
323
await fetch ( `${ pingHostProtocol } ://${ hostAndPath } ` , {
325
324
mode : 'no-cors' ,
326
325
} )
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 ( )
331
345
}
332
346
}
333
347
}
334
348
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
+
335
365
const sheetsMap = new Map < string , HTMLStyleElement > ( )
336
366
// all css imports should be inserted at the same position
337
367
// because after build it will be a single css file
0 commit comments