From de259f45ab61fea4e70d5c095d2e4a82b2a9fdd8 Mon Sep 17 00:00:00 2001
From: Christoph Reiter <reiter.christoph@gmail.com>
Date: Thu, 3 Oct 2019 15:28:59 +0200
Subject: [PATCH] Add icon request caching

We now only create one request per icon.
---
 packages/common/vpu-common-demo.js |  3 ++-
 packages/common/vpu-icon.js        | 23 +++++++++++++++++++++--
 2 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/packages/common/vpu-common-demo.js b/packages/common/vpu-common-demo.js
index 5c21f003..d790321c 100644
--- a/packages/common/vpu-common-demo.js
+++ b/packages/common/vpu-common-demo.js
@@ -95,7 +95,8 @@ class VpuCommonDemo extends VPULitElement {
                         <p style="font-size: 2em; color: orange">Foo <vpu-icon name="cloudnetwork"></vpu-icon> bar</p>
                         <span style="background-color: #000"><a href="#" style=" color: #fff">foobar</a></span>
                         <br>
-                        <vpu-icon style="color: green; height: 50px; border: #000 solid 1px"></vpu-icon>
+
+                        ${(new Array(50).fill(0)).map(i => html`<vpu-icon style="color: green; width: 50px; height: 50px; border: #000 solid 1px"name="coffee-cup"></vpu-icon>`)}
                     </div>
                 </div>
                 <div class="container">
diff --git a/packages/common/vpu-icon.js b/packages/common/vpu-icon.js
index 67f4fd97..f908e20f 100644
--- a/packages/common/vpu-icon.js
+++ b/packages/common/vpu-icon.js
@@ -41,6 +41,7 @@ export function getIconCSS(name) {
 
 async function getSVGTextElement(name) {
     const iconURL = getIconSVGURL(name);
+
     const response = await fetch(iconURL);
     if (!response.ok) {
         return unsafeHTML(errorIcon);
@@ -53,10 +54,28 @@ async function getSVGTextElement(name) {
     return unsafeHTML(text);
 }
 
+const iconCache =  {};
+
+/**
+ * Avoid lots of requests in case an icon is used multiple times on the same page.
+ *
+ * @param {string} name
+ */
+async function getSVGTextElementCached(name) {
+    if (iconCache[name] === undefined) {
+        let promise = getSVGTextElement(name);
+        iconCache[name] = promise;
+        return promise;
+    } else {
+        return iconCache[name];
+    }
+}
+
 /**
- * For icon names see https://materialdesignicons.com/
+ * For icon names see https://lineicons.com
  */
 class Icon extends LitElement {
+
     constructor() {
         super();
         this.name = "bolt";
@@ -88,7 +107,7 @@ class Icon extends LitElement {
     } 
 
     render() {
-        let svg = getSVGTextElement(this.name);
+        let svg = getSVGTextElementCached(this.name);
         return html`
             ${until(svg)}
         `;
-- 
GitLab