|
1 | 1 | class SearchInput { |
2 | 2 |
|
3 | 3 | constructor(elem) { |
| 4 | + this.prefetchLinks = new Set(); |
| 5 | + |
4 | 6 | elem.addEventListener("input", () => { |
5 | 7 | this.update(elem.value.trim().toLowerCase()); |
6 | 8 | }); |
@@ -60,7 +62,7 @@ class SearchInput { |
60 | 62 | } |
61 | 63 |
|
62 | 64 | moveSelection(direction) { |
63 | | - let elems = document.querySelectorAll(this.selectionItemsQuery()) |
| 65 | + let elems = document.querySelectorAll(this.selectionItemsQuery()); |
64 | 66 |
|
65 | 67 | if(elems.length === 0) { return; } |
66 | 68 |
|
@@ -101,4 +103,37 @@ class SearchInput { |
101 | 103 | url.searchParams.set("q", query); |
102 | 104 | history.replaceState({}, "", url.href); |
103 | 105 | } |
| 106 | + |
| 107 | + afterUpdate() { |
| 108 | + if (this.prefetchLastTimeout !== undefined) { |
| 109 | + clearTimeout(this.prefetchLastTimeout); |
| 110 | + this.prefetchLastTimeout = undefined; |
| 111 | + } |
| 112 | + |
| 113 | + // If the search shows ≤ 5 items, add a prefetch header after 200ms. |
| 114 | + |
| 115 | + let elems = document.querySelectorAll(this.selectionItemsQuery()); |
| 116 | + |
| 117 | + if(elems.length === 0 || elems.length > 5) { |
| 118 | + return; |
| 119 | + } |
| 120 | + |
| 121 | + const prefetchLinks = this.prefetchLinks; |
| 122 | + this.prefetchLastTimeout = setTimeout(function() { |
| 123 | + for (const elem of elems) { |
| 124 | + const a = elem.matches("a") ? elem : elem.querySelector("a[href]"); |
| 125 | + if (a !== null) { |
| 126 | + const href = a.href; |
| 127 | + if (!prefetchLinks.has(href)) { |
| 128 | + prefetchLinks.add(href); |
| 129 | + |
| 130 | + const link = document.createElement("link"); |
| 131 | + link.rel = "prefetch"; |
| 132 | + link.href = href; |
| 133 | + document.head.appendChild(link); |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | + }, 200); |
| 138 | + } |
104 | 139 | } |
0 commit comments