fix(post): fetch code lazily
This commit is contained in:
parent
ee3a3b61a2
commit
ed83255604
10 changed files with 209 additions and 172 deletions
|
|
@ -20,3 +20,39 @@ document.addEventListener("DOMContentLoaded", () => {
|
|||
document.querySelectorAll(".post-article h2").forEach(setStyle);
|
||||
document.querySelectorAll(".post-article h3").forEach(setStyle);
|
||||
});
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
document.querySelectorAll(".code").forEach(loadCode);
|
||||
});
|
||||
|
||||
async function loadCode(e) {
|
||||
const file = e.dataset.file;
|
||||
const language = file.substring(file.lastIndexOf(".") + 1);
|
||||
let [_, __, topic, post] = window.location.pathname.split("/");
|
||||
post = post.substring(0, post.lastIndexOf("."));
|
||||
|
||||
try {
|
||||
const path = `/public/code/${topic}/${post}/${file}`;
|
||||
const response = await fetch(path);
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(
|
||||
`Failed to fetch ${path}: ${response.status} ${response.statusText}\n${errorText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const code = await response.text();
|
||||
|
||||
const pre = document.createElement("pre");
|
||||
const codeElement = document.createElement("code");
|
||||
codeElement.className = `language-${language}`;
|
||||
codeElement.textContent = code;
|
||||
|
||||
pre.appendChild(codeElement);
|
||||
e.appendChild(pre);
|
||||
|
||||
Prism.highlightElement(codeElement);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue