Turbo Drive - Cache Lifecycle

Tweak Turbo Drive's cache lifecycle to improve user experience when navigating.

View Solution on Patreon
Turbo Drive - Cache Lifecycle

Premise

One of the most prominent sources of confusion when it comes to understanding Turbo Drive is how it caches content to be restored when you navigate by browser history (i.e., the back and forward buttons of your browser).

Back in the days of jQuery it was especially dreaded, because many jQuery plugins silently rig stuff onto your DOM on page load, but Turbo(links) caching discards all attached event listeners and associated data from your page.

Starting Point

The StackBlitz example for this challenge simulates a third party JavaScript library injecting HTML elements on turbo:load using a Greeter object. It does nothing more than rendering a friendly, time-sensitive greeting and a (randomized) weather report:

The problem arising with caching can be observed in the GIF below (I’ve added a server-side delay to simulate a slow page load): Upon navigation to a page that has an equivalent cache entry, a stale portion of the DOM (an old greeting) is loaded.

We can use the turbo:before-cache event to modify the DOM before it is written to the cache.

Challenges

Caveats

  • Ensure not to inadvertently alter uninvolved parts of the DOM.

Teaser

  • Can you think of any other scenarios where a cached page might be more of a hinderance than an enhancement? (Hint: think of content-heavy pages that load a lot of assets)

More from

Optimistic UI with Turbo 8 Morphs
26 March 2024

Provide Optimistic UI updates using inline Turbo Stream Actions, and reconcile using Turbo 8 Morphs

Turbo Drive - Conditional InstantClick
13 February 2024

Conditionally opt out of Turbo Drive InstantClick using the Strategy pattern

Turbo Drive - Re-Use the Turbo Progress Bar
18 July 2023

Update the progress bar according to some background process' progress.

Cookies
essential