From 6aa795b855cbff1b09cb669e61a42eff97f04f47 Mon Sep 17 00:00:00 2001 From: Saif Ur Rehman Date: Mon, 23 Oct 2023 00:25:42 +0500 Subject: [PATCH] perf(remove_script_and_style): caching for performance --- frappe/public/js/frappe/dom.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/frappe/public/js/frappe/dom.js b/frappe/public/js/frappe/dom.js index 203e5bde7a..0b6dbf0eb8 100644 --- a/frappe/public/js/frappe/dom.js +++ b/frappe/public/js/frappe/dom.js @@ -32,7 +32,26 @@ frappe.dom = { // execute the script globally document.getElementsByTagName("head")[0].appendChild(el); }, + + _remove_script_and_style_cache: {}, + remove_script_and_style: function (txt) { + // do not parse if html tag not found (for performance and cache memory reduction) + if (!txt || !txt.includes("<")) { + return txt; + } + + // cache already processed strings since DOMParser.parseFromString is relatively slow + let cached = this._remove_script_and_style_cache[txt]; + if (cached) { + // true means no evil tags, return string as is undisturbed + if (cached === true) { + return txt; + } else { + return cached; + } + } + const evil_tags = ["script", "style", "noscript", "title", "meta", "base", "head"]; const parser = new DOMParser(); const doc = parser.parseFromString(txt, "text/html"); @@ -55,9 +74,11 @@ frappe.dom = { } if (found) { + this._remove_script_and_style_cache[txt] = body.innerHTML; return body.innerHTML; } else { // don't disturb + this._remove_script_and_style_cache[txt] = true; return txt; } },