RSS Feed

Syntax highlighting in tumblr, the fast & clever way



The first thing you usually do to customize your new techy blog is adding support for code blocks with syntax highlighting.

Now, some of us like to write our tumblr posts using markdown (the smart, portable markup language). Markdown also gives us easy means to display code - Backticks ` surround inline code while four-spaces indentation creates a code block. It also escapes HTML tags for you (how considerate).

Example code block, highlighted by the code inside it. Pretty recursive.But using markdown you cannot add classes like some syntax highlighters require to declare code language. And anyhow, why bother? I was sure there's a solution which could handles most languages without depending on a manual identification.

Well, turns out there is. Google Code Prettify by Mike Samuel is a lightweight, extensible syntax highlighting module which is being used by Google Code & StackOverflow.

I've even found a post on Trial By Byte with a good snippet for using this tool ontypical tumblr posts with jQuery. But I want something more performant, so I 'ported' it to use require.js, the infamous async resource loader.

I've also optimized the code a little bit. If no code blocks are found in the page, the javascript doesn't even load; And I've tweaked the code a little bit to be more succint.

The Code — Google Code Prettify w/ Require.js & jQuery

In the <head>section (loading this async is an overkill IMO):

	<link href="" rel="stylesheet" type="text/css" />

And wherever you want in the <body>, preferably near the end:

<script src=""></script><script>
require([""], function() {
    $(function() {
        var codeBlocks = $('pre code');
        // only if code blocks were found, bring in the prettifier ...
        if (codeBlocks.length) {
            require([''], function() {

Voila! Code blocks are automatically highlighted, blazing fast. Any feedback, questions and comments is welcome.

What do you think?