Skip to content

s9e/hljs-loader

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

69 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

hljs-loader is a small (3 KB) script that can be added to any webpage to automatically load and run highlight.js on all pre > code blocks. It automatically loads additional languages specified via the first lang-* or language-* class name of each code block.

Usage

Add this anywhere to your HTML page:

<script defer src="https://cdn.jsdelivr.net/gh/s9e/hljs-loader@1.0.34/loader.min.js"
        crossorigin="anonymous"
        integrity="sha384-E9ssooeJ4kPel3JD7st0BgS50OLWFEdg4ZOp8lYPy52ctQazOIV37TCvzV8l4cYG"></script>

Configuration

No configuration is required but a number of options are available and can be set on the script element that loads this script.

<script defer src="https://cdn.jsdelivr.net/gh/s9e/hljs-loader@1.0.34/loader.min.js"
        crossorigin="anonymous"
        data-hljs-observe="body"
        data-hljs-options='{"classPrefix":""}'
        data-hljs-style="github"
        data-hljs-url="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/"
        integrity="sha384-E9ssooeJ4kPel3JD7st0BgS50OLWFEdg4ZOp8lYPy52ctQazOIV37TCvzV8l4cYG"></script>
data-hljs-observe
The value should be a CSS selector such as body or #content. The first element that matches this selector will be observed for changes via a MutationObserver instance and new code blocks will be automatically highlighted.
data-hljs-options
The value should be a JSON-encoded object that will be passed to hljs.configure().
data-hljs-style
Name of the highlight.js style to load. If set to none, no style will be loaded. Defaults to default.
data-hljs-url
The root URL used for loading highlight.js files. Defaults to jsDelivr's URL.

API

By default, all code blocks are highlighted when the library is loaded and you do not need to call the library explicitly. However, there may be some situations where you want to manually trigger highlighting or observe a section of the page for new code blocks.

hljsLoader.highlightBlocks(element)
Highlight all blocks in element's subtree. New languages may be loaded and some blocks may be highlighted asynchronously.
hljsLoader.highlightBlocks(document.body);
hljsLoader.observe(selector)
Observe the first element that matches given CSS selector and automatically highlight new code blocks.
hljsLoader.observe('#id');
hljsLoader.disconnect()
Disconnect the observer and stop looking for new code blocks.