Prism Js not working on page loaded by turbo
Prism Js performs the syntax highlighting on DOMContentLoaded, and this only happens once for applications rendered by Turbo.
Therefore something like this shows up when you navigate.
When you perform a hard refresh, it works again.
To make Prism Js work as intended, we can first disable the auto-highlighting feature. This needs to be done before importing the prism library.
window.Prism = window.Prism || {};
window.Prism.manual = true;
import 'prism'
Next, we create a stimulus controller to manually execute the highlighting.
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
connect() {
Prism.highlightAll();
}
}
Finally, attach this controller to the <div> that holds your contents.
<div class="article" data-controller="prism">
</div>
AI Summary
gpt-4o-2024-05-13
2024-07-16 00:41:26
Turbo applications only trigger Prism.js syntax highlighting on page load, causing issues on navigation. A solution involves disabling auto-highlighting, manually executing with a Stimulus controller, and attaching it to document sections for consistent functionality.
Chrome On-device AI
2024-11-09 06:25:55
Share Article