Code Highlighting via Prism.js
Every once in a while, I share code snippets or development tutorials on the blog. Up until recently, I was using a plugin to handle code highlighting. (That’s where the code blocks have their own fancy code styling.) But then I discovered my plugin was causing a conflict with another part of my site, so I needed a different solution.
As it turns out, there was a simple solution already out there — a JavaScript plugin called Prism.js.
Prism.js is lightweight — meaning it won’t hurt your site’s performance. You can customize it with your choice of six different preset themes.
For this site, I’m using the Okaidia theme, which as the developers out there may know, closely resembles the default theme of Sublime Text, a popular code editor.
If you’re a web developer, all you need to get started with Prism.js is head over to their Download page, and choose what components you want to use.
You only need to download the themes you want to use, and the languages you want to target. Unzip the CSS and JavaScript files. Add these files to your server, link to them in your pages, and write yourpre
and/or code
tags and code blocks how you would normally.
Pros To Using Prism
Inline code highlighting is also supported. Need to add line numbers or highlight certain lines? You can add plugins to your Prism.js build on the Download page.
Since Prism doesn’t rely on library-specific CSS classes, you can stop using Prism for code highlighting at any time without suffering any effects to your layout or presentation.
Most of the code highlighting plugins for WordPress already use Prism, but the majority of these plugins aren’t updated regularly.
Cons To Using Prism
The biggest drawback to using Prism is that pre-existing HTML tags are stripped off by default. One way around this is the write the angular brackets (<
and >
) as HTML entities. There are other ways around this, but this is the most bulletproof.
Conclusion
Prism.js allows you to get rid of plugins that do the same thing, while giving you more control over how you display code blocks in your web development articles.