Turbolinks for Starlette

Written by Walter on 31/01/2021

< >

Turbolinks is well known by the rails community. However you can use it to speed up Starlette, Django or Flask served pages too. We only need a few steps to make turbolinks work for any web application. 

In your npm packages add the turbolinks javascript package.

npm install turbolinks

Then in your main application.js you just add a new event listener. Here I made a distinction between first load and any subsequent pageloads.


document.addEventListener("turbolinks:load", function(event) {

jQuery(window).on('load', function(){

Automatically turbolinks changes the behaviour of all your href tags. Instead of doing a full page load, it now loads the html only and replaces the content inline. The major speed improvement comes from the fact your javascript does not need to be reloaded, re-parsed and executed on each page. You only load some html and execute the 'on-load' code.

Sometimes you need to follow a link programatically. You can do that like so:


Applying this technique drastically speeded up my starlette pages. Hope this helps anyone else that wants to improve their page loading times.

Disabling turbolinks

Some pages however need a full pageload. For instance if they load a completely different js framework. One example on this domain is the WebTurtle IDE. For this we have several options to disable turbolink behaviour on tags:

// disable turbolinks for this one link
<a href="/" data-turbolinks="false">Disabled</a>

// disable turbolinks for all links nested within the div tag
<div data-turbolinks="false">
  <a href="/">I'm disabled</a>
  <a href="/">I'm also disabled</a>

// re-enable specific link when ancestor has disabled turbolinks
<div data-turbolinks="false">
  <a href="/">I'm disabled</a>
  <a href="/" data-turbolinks="true">I'm re-enabled</a>

Back to archive