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
- Use the turbo:before-cache event to tweak the content of the page beforeit is written to the cache (https://stackblitz.com/edit/turbo-drive-cache-lifecycle?file=index.html,page2.html,app.js%3AL36).
- Are there other ways to discard elements of the DOM from being cached (see the guide).
- When would you choose one way over the other?
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)