Make a static site snappier with Turbo

Hotwire is a pattern and set of tools from Basecamp, which is also home to the creator of Ruby on Rails. The idea is to send HTML from the server to the web browser instead of JSON. This helps make the client-side code's work easier: instead of parsing JSON and rendering HTML, the client-side code only has to insert the HTML it receives into the correct spot on the page.

Of course it's not that simple, and digging into Turbo, the simplest package within the Hotwire library, can make your head spin from the complexity. Within Turbo is an even smaller package called Turbo Drive, though, which is an easy entry point to Hotwire and can be included in your site very simply.


What does Turbo Drive do?

Turbo Drive intercepts link clicks and form submissions within your site and changes them from a typical full-page reload into a SPA-like page navigation. Turbo's Javascript makes the GET request or form submission itself (instead of the browser doing it natively) and swaps out the page content with the server's HTML response. This can give the impression of an instant page load and speed up navigation.

Using Turbo Drive in a static site

The great part about Turbo Drive is that all you need to do is add a <script> tag to your HTML's <head> element. At the time of writing, you can find this at the top of this page:

<head>
    ...
    <script defer src="/static/project/js/turbo.1dd844a66769.js"></script>
</head>

That's all you need to start using Turbo Drive (although you'll have a different link, see how to install Turbo in your application). If any page navigation takes longer than 500ms, Turbo Drive will show a progress bar at the top of your screen. Most static site requests are shorter than this, however, so to see Turbo Drive in action you can look at the <head> element as you navigate. You'll see new stylesheet <link>s get added dynamically, which doesn't happen in a normal, full-page-reload navigation.

If I find an excuse to use the more complicated parts of Hotwire and Turbo in the future, I'll write about them here.

Note: I'm no longer using Turbo on this site. It just isn't needed.