Highlight.js
Highlight.js is a syntax highlighter written in JavaScript. It works in the browser as well as on the server. It works with pretty much any markup, doesn't depend on any framework and has automatic language detection.
Getting Started
The bare minimum for using highlight.js on a web page is linking to the library along with one of the styles and callinginitHighlightingOnLoad
1
2
3<link rel="stylesheet" href="/path/to/styles/default.css">
<script src="/path/to/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
This will find and highlight code inside of<pre><code>
class
1<pre><code class="html">...</code></pre>
The list of supported language classes is available in thelanguage-
lang-
To disable highlighting altogether use thenohighlight
1<pre><code class="nohighlight">...</code></pre>
Custom Initialization
When you need a bit more control over the initialization of highlight.js, you can use thehighlightBlock
configure
Here's an equivalent way to callinginitHighlightingOnLoad
1
2
3
4
5$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
You can use any tags instead of<pre><code>
<br>
1
2
3
4
5hljs.configure({useBR: true});
$('div.code').each(function(i, block) {
hljs.highlightBlock(block);
});
For other options refer to the documentation forconfigure
Web Workers
You can run highlighting inside a web worker to avoid freezing the browser window while dealing with very big chunks of code.
In your main script:
1
2
3
4
5
6addEventListener('load', function() {
var code = document.querySelector('#code');
var worker = new Worker('worker.js');
worker.onmessage = function(event) { code.innerHTML = event.data; }
worker.postMessage(code.textContent);
})
In worker.js:
1
2
3
4
5onmessage = function(event) {
importScripts('<path>/highlight.pack.js');
var result = self.hljs.highlightAuto(event.data);
postMessage(result.value);
}
Getting the Library
You can get highlight.js as a hosted, or custom-build, browser script or as a server module. Right out of the box the browser script supports both AMD and CommonJS, so if you wish you can use RequireJS or Browserify without having to build from source. The server module also works perfectly fine with Browserify, but there is the option to use a build specific to browsers rather than something meant for a server. Head over to the
Don't link to GitHub directly.
The CDN-hosted package doesn't have all the languages.
1<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.4.0/languages/go.min.js"></script>
On Almond.
1r.js -o name=hljs paths.hljs=/path/to/highlight out=highlight.js
License
Highlight.js is released under the BSD License. See
Links
The official site for the library is at
Further in-depth documentation for the API and other topics is at