Browse Source

Avoid duplicate downloads when using the same individual template on multiple routes when preloading

Shaun Li 2 years ago
parent
commit
92b2e0cf76
2 changed files with 14 additions and 5 deletions
  1. 1 1
      package.json
  2. 13 4
      src/index.js

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "@shaun/alpinejs-router",
-  "version": "1.1.0",
+  "version": "1.1.1",
   "description": "Easy to use and flexible router for Alpine.js",
   "main": "dist/module.cjs.js",
   "module": "dist/module.esm.js",

+ 13 - 4
src/index.js

@@ -90,16 +90,25 @@ export default function (Alpine) {
 
   const routePatterns = {}
   const templateCaches = {}
+  const inProgress = {}
 
   Alpine.directive('route', (el, { modifiers, expression }, { effect, cleanup }) => {
     if (!modifiers.includes('notfound')) {
       routePatterns[expression] = buildPattern(expression)
     }
 
-    const load = url => fetch(url).then(r => r.text()).then(html => {
-      templateCaches[url] = html
-      el.innerHTML = html
-    })
+    const load = url => {
+      if (inProgress[url]) {
+        inProgress[url].then(html => el.innerHTML = html)
+      } else {
+        inProgress[url] = fetch(url).then(r => r.text()).then(html => {
+          templateCaches[url] = html
+          el.innerHTML = html
+          return html
+        })
+      }
+      return inProgress[url]
+    }
 
     let loading
     if (el.hasAttribute('template.preload')) {