The Back Button Is More Powerful Than You Think
You open a website, scroll down, fill out a form, and navigate to another page.
Then you press Back.
The page appears almost instantly. Your form is still filled out. Your scroll position is exactly where you left it.
You might think the browser reloaded the page and restored some information.
But here's the interesting part: the browser may have preserved the entire page, including its JavaScript execution environment.
No HTML parsing. No component initialization. No JavaScript re-execution.
Welcome to the back/forward cache, or bfcache.
🔴 What Actually Happens When You Navigate Away?
Normally, when you navigate to a new document, the browser can discard the previous page.
Returning to it means constructing a new document, executing its scripts, and rebuilding its state.
Even with resources stored in the HTTP cache, there's still work to do.
But modern browsers have another option.
Instead of destroying the previous page, they can freeze it and preserve it in memory.
This includes:
- The DOM, including changes made by JavaScript.
- The JavaScript heap, including variables, objects, and application state.
- Registered event listeners.
- Form values and scroll position.
- The existing document and its execution context.
When you navigate back, the browser can resume this preserved page.
Think of it as suspending an application rather than closing and reopening it.
And this distinction matters because restoring a page is not the same as loading one.
🟢 HTTP Cache vs. bfcache: Two Completely Different Things
These two caches solve different problems.
Imagine your browser needs to display a page containing HTML, JavaScript, images, and stylesheets.
With the HTTP cache, the browser might already have those resources stored locally.
That's useful. It avoids unnecessary downloads.
But the browser still needs to construct the document and execute its JavaScript.
With bfcache, the browser doesn't need to reconstruct the page at all.
| HTTP cache | Back/forward cache |
|---|---|
| Stores network resources | Preserves an entire page |
| Can avoid downloading files | Can avoid rebuilding the page |
| JavaScript executes on a new load | Existing JavaScript state resumes |
| Used for resource requests | Used for eligible history navigations |
| Controlled partly by HTTP caching rules | Controlled by browser eligibility and lifecycle behavior |
Here's a subtle detail: Cache-Control: no-cache doesn't mean a page cannot enter bfcache.
The HTTP cache and bfcache have different rules.
Even no-store isn't a universal bfcache switch across browsers; support and restrictions vary.
So trying to control bfcache solely through HTTP caching headers is not a reliable strategy.
🔵 Let's See What Happens to JavaScript State
Create a simple page:
<button id="increment">Increment</button>
<p id="result">0</p>
<script>
let count = 0;
document.querySelector("#increment").addEventListener("click", () => {
count++;
document.querySelector("#result").textContent = count;
});
</script>
Click the button five times.
The page displays:
5
Now navigate to another page in the same tab, then press Back.
There are two possible outcomes.
Scenario A: Normal navigation
The browser creates a new document and executes the script again.
let count = 0;
The counter starts at zero.
Scenario B: bfcache restoration
The browser restores the preserved document.
The counter still displays 5.
More importantly, the JavaScript variable count is also still 5.
Click the button again, and the result becomes:
6
Nothing had to reconstruct that state.
The original variable and event listener survived the navigation.
This is what makes bfcache fundamentally different from restoring a form value or scroll position.
It preserves the JavaScript environment itself.
🟣 The Page Lifecycle Isn't Just Load and Unload
A common mental model looks like this:
Load page
↓
Initialize JavaScript
↓
User interacts
↓
Navigate away
↓
Page destroyed
But bfcache introduces another path:
Load page
↓
Initialize JavaScript
↓
User interacts
↓
Navigate away
↓
Page frozen in bfcache
↓
User presses Back
↓
Page resumes
Notice what's missing from the second path?
Initialization.
When a page is restored from bfcache, its scripts aren't executed from the beginning.
That means events such as DOMContentLoaded and load don't fire again.
If your application relies exclusively on those events to refresh its state, it won't necessarily do so when the user returns.
Fortunately, the browser provides lifecycle events specifically useful for this situation.
🟠 Meet pageshow and pagehide
The pageshow event fires when a document is shown, including when it's restored from bfcache.
Its persisted property tells you whether that restoration happened.
window.addEventListener("pageshow", (event) => {
if (event.persisted) {
console.log("Restored from bfcache");
} else {
console.log("Normal page show");
}
});
There's an important distinction here.
pageshow isn't exclusive to bfcache. It also fires during normal page loading.
It's the persisted property that tells you whether the document was restored.
Similarly, pagehide fires when the page is being hidden because of navigation.
window.addEventListener("pagehide", (event) => {
console.log("Leaving page");
if (event.persisted) {
console.log("Browser intends to cache this page");
}
});
But there's a catch.
event.persisted === true on pagehide means the browser intends to preserve the page.
It doesn't guarantee that the page will remain cached.
The browser can evict it later because of memory pressure or other conditions.
That's why you should detect an actual restoration through pageshow, not assume one will happen based on pagehide.
🔴 The Real Problem: Your Application Might Be Outdated
Let's move beyond a counter.
Imagine you're building a dashboard for an online store.
A user opens the inventory page:
Product: Mechanical Keyboard
Available stock: 12
They navigate to the orders page and process an order for three keyboards.
The actual stock is now nine.
Then they press Back.
If the inventory page is restored from bfcache, it may still display:
Available stock: 12
Why?
Because the browser restored the page exactly as it was.
Your original API request didn't run again.
Your application's initialization logic didn't run again.
The browser has no idea that the data on your server changed.
From its perspective, it's simply restoring an existing document.
And this isn't limited to inventory dashboards.
The same problem can affect authentication status, shopping carts, notification counts, account balances, permissions, and other frequently changing information.
bfcache preserves state, not truth.
That's the trade-off.
The browser optimizes navigation speed by restoring the previous state, but your application is responsible for deciding whether that state is still valid.
🟢 Refresh the Data, Not the Entire Page
A tempting solution would be to force a reload whenever the page is restored.
window.addEventListener("pageshow", (event) => {
if (event.persisted) {
window.location.reload();
}
});
Technically, that works.
But it also defeats the performance benefit of bfcache.
You've taken an almost instantaneous restoration and turned it into a full page load.
A better approach is to refresh only the information that needs updating.
async function refreshInventory() {
const response = await fetch("/api/inventory");
if (!response.ok) {
throw new Error("Failed to fetch inventory");
}
const inventory = await response.json();
renderInventory(inventory);
}
window.addEventListener("pageshow", (event) => {
if (event.persisted) {
refreshInventory().catch(console.error);
}
});
Now the page can reappear immediately while its data is updated.
The user doesn't lose their scroll position or local UI state simply because the server-side data needs revalidation.
You can even display the previously available information while the refresh is in progress, provided the UI makes its freshness clear when that matters.
This is similar to stale-while-revalidate strategies used in data fetching.
The key idea is that page restoration and data freshness are separate concerns.
🔵 What Happens to Timers and Pending Work?
Here's where things become more interesting.
Consider this:
setInterval(() => {
console.log("Tick");
}, 1000);
What happens when the page enters bfcache?
Does the interval continue executing in the background?
No.
The page is frozen. Its ordinary JavaScript execution is suspended while it remains cached.
When the page is restored, its JavaScript environment resumes.
But don't assume that every second spent away corresponds to an interval callback.
If your application uses a counter to measure elapsed time, this can cause incorrect results.
For example:
let elapsed = 0;
setInterval(() => {
elapsed++;
}, 1000);
This isn't a reliable way to measure real elapsed time across page suspension.
Instead, calculate the difference between timestamps:
const startedAt = Date.now();
function getElapsedSeconds() {
return Math.floor((Date.now() - startedAt) / 1000);
}
Now the calculation accounts for wall-clock time that passed while the page wasn't executing.
The broader lesson applies to animation loops, polling, scheduled work, and other time-dependent behavior.
A preserved JavaScript environment doesn't mean JavaScript was continuously running.
And some in-flight work, such as certain network operations, can affect whether a page is eligible for bfcache in the first place.
🟣 Can Every Page Use bfcache?
No.
The browser decides whether a page is eligible.
That decision depends on browser implementation, document behavior, available memory, and other conditions.
One historically important example is the unload event.
window.addEventListener("unload", () => {
console.log("Goodbye!");
});
This event is unreliable during navigation, and its presence can prevent bfcache eligibility in some browsers.
Modern browser guidance generally favors avoiding unload.
If you need to observe a page being left, pagehide is usually a better choice.
If you need to save application state as the user switches tabs or leaves, visibilitychange is often more appropriate.
These events aren't interchangeable, though.
visibilitychange can happen when the user simply switches tabs, without navigating anywhere.
pagehide is associated with the document being hidden during navigation.
And neither should be treated as a guaranteed opportunity to finish arbitrary asynchronous work.
Another important point: you can't force the browser to cache your page.
You can make your application compatible with bfcache, but the browser ultimately decides whether to preserve it.
🟠 How to Test bfcache in Chrome
You don't have to guess whether your page is being restored.
Chrome DevTools includes a dedicated bfcache testing tool.
- Open the page in Chrome.
- Open DevTools.
- Navigate to Application → Background services → Back/forward cache (the exact location can vary by Chrome version).
- Run the back/forward cache test.
- Inspect whether the page was restored and, if not, the reported reasons.
You can also inspect navigation timing information:
const navigation = performance.getEntriesByType("navigation")[0];
console.log(navigation?.type);
But be careful: a value of "back_forward" indicates a history navigation, not necessarily a bfcache restoration.
A history navigation can still involve loading a new document.
For a direct restoration check, use:
window.addEventListener("pageshow", (event) => {
console.log("From bfcache:", event.persisted);
});
This is the distinction worth remembering when debugging.
Going Back and being restored from bfcache are not synonymous.
⚡ The Takeaway
The Back button isn't necessarily telling the browser to load a previous URL again.
Sometimes it's telling the browser to resume an entire page that never got destroyed.
That's why a page can return instantly with its DOM, JavaScript variables, event listeners, and user interactions intact.
But it also means developers need to think about a lifecycle that doesn't always begin with initialization.
A page can become visible without running its startup code again.
Its data can be stale even though its UI looks perfectly restored.
And its JavaScript can resume after being frozen for an unknown amount of time.
The goal isn't to fight bfcache or force every navigation to reload.
It's to build pages that behave correctly whether they're loaded from scratch or resumed from memory.
Because sometimes the fastest page load is the one that never happens.
🧪 See bfcache in Action
Want to see what actually happens when your browser restores a page instead of reloading it?
Try the interactive bfcache demo. Increment the counter, navigate to Page B, wait a few seconds, and press Back.
If bfcache was used, you'll see that your React state survived, JavaScript timers were suspended, and pageshow.persisted reports true.
Then try a normal reload and compare the results.
Same page. Same code. Completely different navigation behavior.


