Code highlighting in Blogger's dynamic templates

I decided to update the style of my blog recently, and immediately fell in love with new dynamic blog templates. Navigation is easy, and the look is quite slick.

But, as usual, all shiny things have downsides. Since dynamic templates fetch content via ajax, long after the main page is loaded, "conventional" ways to highlight code snippets on page load don't work (and most code highlighting libs only use this method).

And, to make things worse, developers of dynamic templates haven't provided us with hooks to detect the moment of page change. Some brave souls ventured into the depths of template javascript, and some even found the place where user's code can hook to get article change event - but since it's not documented and google developers change the code constantly, this workaround tends to break every several months or so.

Currently, I use simple (as in "quick&dirty") workaround - I simply insert small piece of javascript code directly into each article source:
This code runs every time the article content is loaded, successfully triggering code highlighting. The only downside - I constantly forget to insert this snippet when creating an article, and spend several minutes wondering - "why my code is not highlighted?".

For actual code highlighting, I use awesome Highlight.js - it's extremely simple to use, features language auto-detection and superb API. To get it to work, you only need the following snippet of code inserted into html of your blog template (somewhere in <head>):
<script src="//"></script>
<link rel="stylesheet" href="//"></link>
<script src="//"></script>
  function runCodeHighlighting() {
P.S. Previously, I used Github's gists to embed code in my posts, but it seems that it is incompatible with dynamic templates - code doesn't show up completely.


Popular posts from this blog

How to create your own simple 3D render engine in pure Java

Solving quadruple dependency injection problem in Angular

Better CLI option parsing in Scala