Turbo Drive - Conditional InstantClick

Conditionally opt out of Turbo Drive InstantClick using the Strategy pattern

View Solution on Patreon
Turbo Drive - Conditional InstantClick

Premise

Turbo 8 has arrived, and with it InstantClick behavior! The good news is that this will speed up navigation in a lot of cases tremendously. Beware though that it’s enabled by default on all navigations, which can cause stress for your app servers.

There are options to either opt-out globally, or on a per-element basis with data-turbo-prefetch="false". However, this requires you to declare it on each link element individually, or opt out on a parent (e.g. <div>) element and then reenable for every link that requires it inside it.

What, though, if we want an implicit opt-out? This could be useful

  • for sub-routes, e.g. an /admin namespace, etc.
  • for link elements that trigger interactions, e.g. via TurboBoost Commands

Starting Point

We are going to simulate these cases in a small demo app. It has two sub-pages, /authors/author.html, and /posts/post.html. It also features a “Like” link with a data-turbo-command attribute indicating that it is used by TurboBoost:

https://stackblitz.com/edit/turbo-drive-opt-in-instantclick?file=index.html%3AL38

As you can see in this GIF, prefetches are triggered on each of those links:

A browser window displaying rapid prefetching of links

Challenge

Come up with a solution that

  • triggers a prefetch for the post, but not the author link
  • doesn’t prefetch the “Like” link
  • You will likely want to use the turbo:before-prefetch event for this:

https://stackblitz.com/edit/turbo-drive-opt-in-instantclick?file=index.html,app.js%3AL6

Teaser

How could you make this pattern extensible?

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 - Re-Use the Turbo Progress Bar
18 July 2023

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

Turbo Drive - Form Activity Indicators
06 June 2023

Provide user feedback for slow running form submits.

Cookies
essential