From 37a3f94dec3b491d4fcefa20304fbd5970cbffa4 Mon Sep 17 00:00:00 2001 From: Niko Date: Mon, 14 Feb 2022 11:15:13 +0100 Subject: [PATCH] Improved app.template to get/set many templates --- web/src/app/js/app.js | 31 ++++++++++++++++++++++++++----- web/src/app/js/base.js | 1 + 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/web/src/app/js/app.js b/web/src/app/js/app.js index d918932..91f2acf 100644 --- a/web/src/app/js/app.js +++ b/web/src/app/js/app.js @@ -8,17 +8,38 @@ app.script = function(name, cback) { } app.template = { - load: function(name, cback) { + loadMany: async function(names, cback) { + var templates = []; + for (var i = 0; i < names.length; i++) { + app.template.load(names[i], function(tpl) { + templates.push(tpl); + }); + } + var j = 0; + while (templates.length < names.length && j < 10) { + await sleep(1000); + j++; + } + return templates; + }, + set: function(name, html) { + name = 'template__'+name.replaceAll('.', '-'); + window.__cache_templates[name] = html; + }, + get: function(name) { + name = 'template__'+name.replaceAll('.', '-'); if (window.__cache_templates === undefined) window.__cache_templates = {}; + return window.__cache_templates[name]; + }, + load: function(name, cback) { file = app.vars.js_dir + '/templates/' + name.replaceAll('.', '/') + '.html'; - name = 'template__'+name.replaceAll('.', '-'); - if (window.__cache_templates[name] !== undefined) - return cback(window.__cache_templates[name]); + if (app.template.get(name) !== undefined) + return cback(app.template.get(name)); http.get(file, {}, function(html) { html = html.trim(); - window.__cache_templates[name] = html; + app.template.set(name, html); return cback(html); }); }, diff --git a/web/src/app/js/base.js b/web/src/app/js/base.js index dbd9b10..b7be670 100644 --- a/web/src/app/js/base.js +++ b/web/src/app/js/base.js @@ -43,6 +43,7 @@ function loadScript(id, file, cback) { function getNormalizedURI() { return window.location.pathname.replace(/\/+?$/, '') } function capitalize(s) { return s.charAt(0).toUpperCase() + s.substr(1) } +function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } function JSON_to_URLEncoded(element,key,list) { var list = list || [];