Back/Forward Cache (bfcache): In-Memory Freezing & BFCache Ineligibility
- Last updated
- Prerequisites:
- Browser navigation lifecycle
- Event loop task execution
- browser
- bfcache
- performance
- pageshow
- pagehide
- navigation
Read at your depth
The practical view
The Back/Forward Cache (bfcache) is an in-memory snapshot of a completely rendered page (including the live JavaScript execution state and DOM). When a user navigates away and clicks 'Back', the page is restored instantly without running scripts from scratch or making network requests. You listen to `pageshow` and `pagehide` events and check `event.persisted` to detect if the page was restored from or saved to the bfcache.
The same idea in other frameworks
Re-subscribing to live data or resetting stale timers in `window.addEventListener('pageshow', ...)`.Re-authenticating user tokens when `event.persisted` is true in root component lifecycle.`onMounted` does not re-run on bfcache restore; use `pageshow` event listeners.SvelteKit snapshots coordinate with bfcache to preserve form input and scroll positions.Legacy vs modern
Unload Listener (bfcache blocker) vs Pagehide Lifecycle
`window.addEventListener('unload')` completely disables bfcache; replacing it with `pagehide` enables instant 0ms back-navigation.
window.addEventListener('unload', cleanup); // ❌ Disables bfcache entirelywindow.addEventListener('pagehide', ...); // ✅ NEW: Fully bfcache compatibleInterview gotchas
Context
Tests awareness of legacy DOM APIs and performance anti-patterns.
The mechanical answer
Adding an `unload` event listener (`window.addEventListener('unload', ...)`). The `unload` event is incompatible with bfcache because it implies the page is being permanently destroyed. Browsers cannot guarantee that code in `unload` won't leave state in an un-resumable condition, so they disqualify the page from bfcache. The modern replacement is the `pagehide` event.
Trap
Even third-party libraries (like legacy analytics or ad scripts) adding an `unload` listener will silently destroy bfcache eligibility for your entire application.
Context
This tests understanding of browser execution lifecycle during back-navigation.
The mechanical answer
No. When a page is restored from bfcache, the DOM was never destroyed and scripts do not re-execute from top to bottom. Neither `DOMContentLoaded`, `load`, nor component mount hooks (`useEffect`, `onMounted`) run. The only event guaranteed to fire is `pageshow` with `event.persisted === true`.
Trap
If you rely on `onMount` / `useEffect` to fetch fresh user data or check authentication, back-navigation from bfcache may display stale private data unless re-validated in a `pageshow` listener.