bfcache — Native Browser Back/Forward Cache

Shared by
Published

Learn how to use bfcache to significantly improve the browsing experience for users — especially those with slower connections.

What is bfcache?

Back/forward cache (or bfcache) is a browser optimization that enables instant back and forwards navigation. It significantly improves the browsing experience for users—especially those with slower networks or devices.

bfcache is an in-memory cache that stores a complete snapshot of a page (including the JavaScript heap) as the user is navigating away. With the entire page in memory, the browser can quickly and easily restore it if the user decides to return.

Without bfcache

A new request is initiated to load the previous page, and, depending on how well that page has been optimized for repeat visits, the browser might have to re-download, re-parse, and re-execute some (or all) of resources it just downloaded.

With bfcache

Loading the previous page is essentially instant, because the entire page can be restored from memory, without having to go to the network at all.

In the video above, the example with bfcache is quite a bit faster than the example without it.

How to Use bfcache

One of the best things about bfcache is it’s an optimization method browsers do automatically, though it’s still important for developers to know when it’s happening so they can optimize their pages for it and adjust any metrics or performance measurement accordingly.

Learn more about bfcache, how to use it and the events it fires by reading Philip Walton’s in-depth article on web.dev.

Using Google Analytics? Read this.

If you don’t want your pageview counts to go down due to Chrome enabling bfcache, you can report bfcache restores as pageviews (recommended) by listening to the pageshow event and checking the persisted property.

The following example shows how to do this with Google Analytics; the logic should be similar for other analytics tools:

// Send a pageview when the page is first loaded.
gtag('event', 'page_view')

window.addEventListener('pageshow', function(event) {
  if (event.persisted === true) {
    // Send another pageview if the page is restored from bfcache.
    gtag('event', 'page_view')
  }
});

Join the conversation.

Your email address will not be published. Required fields are marked *

All comments posted on 'bfcache — Native Browser Back/Forward Cache' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.