From 143b9b685d120e48b87db0a110794c007844d543 Mon Sep 17 00:00:00 2001 From: Michael Fabian 'Xaymar' Dirks Date: Wed, 5 Jun 2024 06:45:22 +0200 Subject: [PATCH] Only load languages that are actually used Firefox doesn't like 429 Too Many Requests at all --- assets/js/highlight.mjs | 78 ++++++++++++----------------------------- 1 file changed, 22 insertions(+), 56 deletions(-) diff --git a/assets/js/highlight.mjs b/assets/js/highlight.mjs index 7d359e4..442bb22 100644 --- a/assets/js/highlight.mjs +++ b/assets/js/highlight.mjs @@ -2,69 +2,19 @@ // Highlight.JS: https://highlightjs.org/ async function initializeHighlightJS() { - const languageRE = /\blanguage-([a-zA-Z0-9_\-]+)\b/gi; const noLanguageRE = /\bno-language\b/gi; - const languages = [ - "apache", - "asciidoc", - "autohotkey", - "bash", - "basic", - "c", - "cmake", - "cpp", - "csharp", - "css", - "d", - "diff", - "gcode", - "glsl", - "go", - "gradle", - "graphql", - "http", - "ini", - "java", - "javascript", - "json", - "kotlin", - "latex", - "less", - "llvm", - "lua", - "makefile", - "markdown", - "nginx", - "objectivec", - "oxygene", - "perl", - "php", - "php-template", - "plaintext", - "protobuf", - "python", - "python-repl", - "r", - "ruby", - "rust", - "scss", - "shell", - "sql", - "swift", - "typescript", - "vbnet", - "wasm", - "xml", - "yaml", - ]; + const languages = new Set(); const selector = "code.block[class*=\"language\"]"; + const blocks = document.querySelectorAll(selector); - if (document.querySelectorAll(selector).length == 0) { + // Early-Exit if there's nothing to highlight anyway to reduce waste. + if (blocks.length == 0) { console.log("highlight.JS: Skipping, as it is not needed here."); return; } + // Load and configure highlight.JS console.log("highlight.JS: Loading..."); let highlightJS = await import("./highlightjs/highlight.mjs"); window.highlightJS = highlightJS.default; @@ -77,6 +27,17 @@ async function initializeHighlightJS() { "throwUnescapedHTML": true, }); + // Find all languages used. + for (let block of blocks) { + for (let classname of block.classList) { + for (let match of classname.matchAll(languageRE)) { + if (match.length > 0) { + languages.add(match[1]); + } + } + } + } + // Import all languages. let langs = []; for (let lang of languages) { @@ -90,6 +51,7 @@ async function initializeHighlightJS() { let err = null; for (let attempt = 1; attempt <= 5; attempt++) { try { + // Firefox breaks here because it hates 429 Too Many Requests. All other browsers work. mod = await import(`./highlightjs/languages/${lang}.min.js`); break; } catch (ex) { @@ -114,7 +76,11 @@ async function initializeHighlightJS() { // Highlight everything. function highlightAllCode() { console.log(`highlight.JS: Applying highlighting all valid code blocks...`); - window.highlightJS.highlightAll(); + try { + window.highlightJS.highlightAll(); + } catch (ex) { + console.error(`highlight.JS: ${ex}`); + } }; if (document.readyState === "complete" || document.readyState === "loaded"