Will Ridgers

instantclick and highlight.js

· web javascript tips

If you’re trying to use highlight.js and InstantClick you’ll soon run into problems. InstantClick works by fetching the page you’re trying to view with an AJAX request, and replacing the <body> and <title> of the page you’re already viewing. highlight.js can break because the one way to use it is by calling hljs.initHighlightingOnLoad(); which works the first time, but not on subsequent page loads with InstantClick — because the on load event isn’t fired again.

The solution is to use InstantClick’s change event, which fires when the page is first loaded, and on subsequent ‘fake’ page loads.

InstantClick.on('change', function() {
  var blocks = document.querySelectorAll('pre code');

  for (var i = 0; i < blocks.length; i++) {
    hljs.highlightBlock(blocks[i]);
  }
});