Files
discourse/app/assets/javascripts/highlightjs-worker.js
David Taylor d09f283e91 PERF: Move highlightjs to a background worker, and add result cache (#10191)
Syntax highlighting is a CPU-intensive process which we run a lot while rendering posts and while using the composer preview. Moving it to a background worker releases the main thread to the browser, which makes the UX much smoother.
2020-07-15 12:48:07 +01:00

48 lines
1.1 KiB
JavaScript

// Standalone worker for highlightjs syntax generation
// The highlightjs path changes based on site settings,
// so we wait for Discourse to pass the path into the worker
const loadHighlightJs = path => {
self.importScripts(path);
};
const highlight = ({ id, text, language }) => {
if (!self.hljs) {
throw "HighlightJS is not loaded";
}
const result = language
? self.hljs.highlight(language, text, true).value
: self.hljs.highlightAuto(text).value;
postMessage({
type: "highlightResult",
id: id,
result: result
});
};
const registerLanguage = ({ name, definition }) => {
if (!self.hljs) {
throw "HighlightJS is not loaded";
}
self.hljs.registerLanguage(name, () => {
return definition;
});
};
onmessage = event => {
const data = event.data;
const messageType = data.type;
if (messageType === "loadHighlightJs") {
loadHighlightJs(data.path);
} else if (messageType === "registerLanguage") {
registerLanguage(data);
} else if (messageType === "highlight") {
highlight(data);
} else {
throw `Unknown message type: ${messageType}`;
}
};