Skip to main content

Sebastiaan Luca

Highlight.js with Turbolinks

April 20, 2020
1 minute read
This blog post was written more than a year ago. Be wary of any technologies that might have changed and if no better alternatives exist at the time of viewing this post.

When you first set up Highlight.js in a Turbolinks application, you might notice your code isn't highlighted anymore.

The reason for this is that Turbolinks reloads only part of the page —what's changed— and we need to tell Higlight.js to reapply on our new content.

We can do that by listening to the Turbolinks load event. In your main JS entry file:

import highlightjs from 'highlight.js/lib/core'
import 'highlight.js/styles/shades-of-purple.css'

// Highlight code on non-Turbolink pages

// Reapply code highlighting on pages loaded with Turbolinks
document.addEventListener('turbolinks:load', function() {
   document.querySelectorAll('pre code').forEach((block) => {