Syntax highlighting as an enhancement

by Michael Scharnagl

This article has been updated the last time on January 5, 2016 and the given information may be not accurate anymore. Feel free to contact me on twitter to get more details.

I never had syntax highlighting for my code examples on this site and thought it is finally time to add one. After looking at some solutions I decided to use Prism as it is well tested and maintained and extensible.

Implementation

Do use Prism you need to include the CSS and JavaScript files you get from the Download page. In my case I saved the CSS I got as prism.scss under the folder vendor and afer running it through Grunt it got compiled with the other SCSS files, compressed and inlined in the head of the site.

After that I added the JavaScript in my footer.php at the very end:

<script defer src="https://justmarkup.com/log/wp-content/themes/justmarkup.com/dist/js/prism.min.js"></script>

Note: I first tried it with the async attribute but this doesn’t work with Prism so I used the defer attribute instead.

With this in place I went through my articles and added class="language-xxx"> to every code element where I want to have syntax highlighting. Finally some pretty code examples on my site. And if the JavaScript doesn’t load for whatever reason, the code blocks are still readable fine, like it was before – in two words – progressive enhancement.

Examples

CSS

.code {border: 1px solid green;}

JavaScript

var Prism = true;

Michael Scharnagl

Portrait Michael Scharnagl

Follow me: @justmarkup

Subscribe to RSS: /feed

A freelance front-end developer focusing on HTML5, CSS, progressive enhancement and web performance.