From c48bc8a76ef9c4c6bf1275249863a4b396e073fe Mon Sep 17 00:00:00 2001 From: valadaptive Date: Sat, 9 Dec 2023 21:29:36 -0500 Subject: [PATCH] Cache compiled Handlebars templates Since we already have a template cache, it makes sense to store the templates in it *after* compiling them, to avoid the overhead of re-compiling them every time we call renderTemplate. I've also changed the cache from an object to a Map--it's more semantically correct, and avoids weird edge cases like a template named "hasOwnProperty" or some other function that exists as an object property. --- public/script.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/public/script.js b/public/script.js index 64cb41752..ee236f448 100644 --- a/public/script.js +++ b/public/script.js @@ -526,14 +526,17 @@ function getUrlSync(url, cache = true) { }).responseText; } -const templateCache = {}; +const templateCache = new Map(); export function renderTemplate(templateId, templateData = {}, sanitize = true, localize = true, fullPath = false) { try { const pathToTemplate = fullPath ? templateId : `/scripts/templates/${templateId}.html`; - const templateContent = (pathToTemplate in templateCache) ? templateCache[pathToTemplate] : getUrlSync(pathToTemplate); - templateCache[pathToTemplate] = templateContent; - const template = Handlebars.compile(templateContent); + let template = templateCache.get(pathToTemplate); + if (!template) { + const templateContent = getUrlSync(pathToTemplate); + template = Handlebars.compile(templateContent); + templateCache.set(pathToTemplate, template); + } let result = template(templateData); if (sanitize) {