All files / lib stale-chunk.ts

88.88% Statements 8/9
88.88% Branches 8/9
66.66% Functions 2/3
87.5% Lines 7/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 241x               1x               3x   5x 4x 4x 4x    
const KEY = 'stale-chunk-reload-at';
 
/**
 * Handler for Vite's `vite:preloadError`: after a deploy, a tab still open on the previous release
 * asks for lazy chunks that are gone (Cloudflare Pages answers 404, see public/_headers), so the route cannot load. Reload
 * once to get the new index.html. A second failure within `windowMs` is left to the route's error
 * page, so a chunk that is really missing does not reload in a loop.
 */
export const reloadOnStaleChunk =
  ({
    storage = sessionStorage,
    reload = () => {
      window.location.reload();
    },
    now = Date.now,
    windowMs = 10_000,
  } = {}) =>
  (event: Event) => {
    if (now() - Number(storage.getItem(KEY) ?? 0) < windowMs) return;
    storage.setItem(KEY, String(now()));
    event.preventDefault();
    reload();
  };