Просмотр исходного кода

Preload the separate template file

Shaun Li 2 лет назад
Родитель
Сommit
a6b6f05935
3 измененных файлов с 22 добавлено и 9 удалено
  1. 2 0
      README.md
  2. 1 1
      package.json
  3. 19 8
      src/index.js

+ 2 - 0
README.md

@@ -184,6 +184,8 @@ Declare routes by creating a template tag with `x-route` attribute.
 </template>
 
 <template x-route="/path/to/route" template="/path/to/template.html"></template>
+<!-- Preload the separate template file -->
+<template x-route="/path/to/route" template.preload="/path/to/template.html"></template>
 
 <!-- When declaring a template that is not found, the path parameter does not need to be specified -->
 <template x-route.notfound>

+ 1 - 1
package.json

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

+ 19 - 8
src/index.js

@@ -96,6 +96,17 @@ export default function (Alpine) {
       routePatterns[expression] = buildPattern(expression)
     }
 
+    const load = url => fetch(url).then(r => r.text()).then(html => {
+      templateCaches[url] = html
+      el.innerHTML = html
+    })
+
+    let loading
+    if (el.hasAttribute('template.preload')) {
+      const url = el.getAttribute('template.preload')
+      loading = load(url).finally(() => loading = false)
+    }
+
     function show () {
       if (el._x_currentIfEl) return el._x_currentIfEl
 
@@ -120,18 +131,18 @@ export default function (Alpine) {
 
       if (el.content.firstElementChild) {
         make()
-      } else if (el.hasAttribute('template')) {
-        const url = el.getAttribute('template')
+      } else if (el.hasAttribute('template') || el.hasAttribute('template.preload')) {
+        const url = el.getAttribute('template') || el.getAttribute('template.preload')
         if (templateCaches[url]) {
           el.innerHTML = templateCaches[url]
           make()
         } else {
-          state.loading = true
-          fetch(url).then(r => r.text()).then(html => {
-            templateCaches[url] = html
-            el.innerHTML = html
-            make()
-          }).finally(() => state.loading = false)
+          if (loading) {
+            loading.then(() => make())
+          } else {
+            state.loading = true
+            load(url).then(() => make()).finally(() => state.loading = false)
+          }
         }
       } else {
         console.error(`Template for '${expression}' is missing`)