Loading SyntaxHighlighter on demand

Sep 01 2009

SyntaxHighlighter is a great JavaScript script, but it lacks one important feature in my opinion.

For this blog, I needed a syntax highlighter for the code examples that will be shown here. I soon found SyntaxHighlighter as I was looking for an unobtrusive JavaScript solution. But there's one thing that I didn't like about it. You need to load all JavaScript files in advance even if you don't need syntax highlighting on a given page. This is not a problem when you're building static pages, because then you can just include the needed JavaScript files yourself. For this blog however I wanted SyntaxHighlighter to be loaded on demand without specifying for which page the SyntaxHighlighter should be loaded.

So I came up with the nifty JavaScript solution below. It uses jQuery because jQuery is already loaded on all pages of this blog. But it shouldn't be so hard to do the same without jQuery.

	function() {

		// only load syntax hilighter when needed
		// So check for any HTML <pre> elements for which the class attribute starts with 'brush'
		if ($("pre[class^=brush]").length > 0) {
			var jsPath = themeUrl + '/js/hilighter/';
			var cssPath = themeUrl + '/css/hilighter/';
			// Defines which languages should be supported
			var brushes = ['Bash','Php','Plain','JScript', 'Sql'];
			var jsBrushes = '';
			for (var i = 0; i < brushes.length; i) {
				jsBrushes  = '<script src="' + jsPath + 'shBrush' + brushes[i] + '.js" type="text/javascript"></script>';
			// Append SyntaxHighlighter scripts to the HTML head
				'<script src="' + jsPath + 'shCore.js" type="text/javascript"></script>' +
				  jsBrushes +
				  '<link rel="stylesheet" href="' + cssPath + 'shCore.css" type="text/css">' +
				  '<link rel="stylesheet" href="' + cssPath + 'shThemeDefault.css" type="text/css">'
			// Apply SyntaxHilighlighter

I think the script is pretty much self-explanatory. First we check if there are one or more PRE-elements having a classname that starts with "brush". If one or more of such PRE-elements exist in our HTML code, the appropriate SyntaxHighlighter CSS and JavaScript files will be loaded by adding script tags to the HTML head.