Lazy-load highlight.js

This commit moves the import of highlight.js into a `require.ensure`
block, that is only executed when a code-block is actually present
in a note. Webpack automatically splits the library into a separate
chunk and loads that on demand.

The call to `hljs.listLanguages()` in `index.js` is also replaced
by a static list. This is important, as `index.js` would otherwise
need to import highlight.js, which would cause the quite big
library to be included into nearly every entrypoint, needlessly
increasing the transferred code size.

Signed-off-by: David Mehren <git@herrmehren.de>
This commit is contained in:
David Mehren 2021-06-06 22:20:29 +02:00
parent 5b8b76135b
commit 7ff685933e
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
3 changed files with 201 additions and 39 deletions

View file

@ -3,7 +3,6 @@
/* global moment, serverurl */
import Prism from 'prismjs'
import hljs from 'highlight.js'
import PDFObject from 'pdfobject'
import S from 'string'
import { saveAs } from 'file-saver'
@ -525,13 +524,19 @@ export function finishView (view) {
value: Prism.highlight(code, Prism.languages.makefile)
}
} else {
code = S(code).unescapeHTML().s
const languages = hljs.listLanguages()
if (!languages.includes(reallang)) {
result = hljs.highlightAuto(code)
} else {
result = hljs.highlight(reallang, code)
}
require.ensure([], function (require) {
const hljs = require('highlight.js')
code = S(code).unescapeHTML().s
const languages = hljs.listLanguages()
if (!languages.includes(reallang)) {
result = hljs.highlightAuto(code)
} else {
result = hljs.highlight(reallang, code)
}
if (codeDiv.length > 0) codeDiv.html(result.value)
else langDiv.html(result.value)
})
return
}
if (codeDiv.length > 0) codeDiv.html(result.value)
else langDiv.html(result.value)