From 619fe67cc5f2bdc09912f2558b0cdccd35e87eff Mon Sep 17 00:00:00 2001 From: Eduard Urbach Date: Sat, 31 Aug 2019 20:29:03 +0900 Subject: [PATCH] Improved SVG icon performance --- scripts/Elements/svg-icon/svg-icon.ts | 30 ++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/scripts/Elements/svg-icon/svg-icon.ts b/scripts/Elements/svg-icon/svg-icon.ts index 9cbebfa3..05a18f19 100644 --- a/scripts/Elements/svg-icon/svg-icon.ts +++ b/scripts/Elements/svg-icon/svg-icon.ts @@ -1,7 +1,7 @@ import Diff from "scripts/Diff" export default class SVGIcon extends HTMLElement { - static cache = new Map>() + static cache = new Map>() static get observedAttributes() { return ["name"] @@ -17,8 +17,18 @@ export default class SVGIcon extends HTMLElement { let cache = SVGIcon.cache.get(this.name) if(cache) { - let text = await cache - Diff.mutations.queue(() => this.innerHTML = text) + let svg = await cache + + Diff.mutations.queue(() => { + // Remove all existing child nodes + while(this.firstChild) { + this.removeChild(this.firstChild) + } + + // Append a clone of the cached SVG node + this.appendChild(svg.cloneNode(true)) + }) + return } @@ -33,8 +43,18 @@ export default class SVGIcon extends HTMLElement { } let text = await response.text() - Diff.mutations.queue(() => this.innerHTML = text) - resolve(text) + + Diff.mutations.queue(() => { + this.innerHTML = text + let svg = this.firstChild + + if(!svg) { + console.warn("Invalid SVG icon:", svg) + return + } + + resolve(svg) + }) })) }