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.
Add this anywhere to your HTML page:
<script defer src="https://cdn.jsdelivr.net/gh/s9e/hljs-loader@1.0.36/loader.min.js"
crossorigin="anonymous"
integrity="sha384-ENgSnUL5UgeHebIZiuTpRAT4+a3licJ29eIcCndVuHFJvncvtdJoQL0XIBStbgl9"></script>
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.36/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.11.0/build/"
integrity="sha384-ENgSnUL5UgeHebIZiuTpRAT4+a3licJ29eIcCndVuHFJvncvtdJoQL0XIBStbgl9"></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 todefault
. data-hljs-url
- The root URL used for loading highlight.js files. Defaults to jsDelivr's URL.
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.