Skip to main content

Sebastiaan Luca

Highlight.js with Turbolinks

April 20, 2020
1 minute read

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
highlightjs.initHighlightingOnLoad()

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