Skip to content

Commit 1466e5d

Browse files
committed
Add prefetch links for search results.
When a search returns 5 or less results, add <link rel="prefetch"> elements to the header, so the browser will have the pages cached if the user open any of them.
1 parent f54a5e6 commit 1466e5d

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

lib/ffdocs/view/javascript/front-search.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ class FrontSearchInput extends SearchInput {
8787
results.appendChild(dt);
8888
results.appendChild(dd);
8989
}
90+
91+
this.afterUpdate();
9092
}
9193

9294
// Extract item data from the links in the <nav>.

lib/ffdocs/view/javascript/nav-search.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ class NavSearchInput extends SearchInput {
7676
elem.classList.add("hidden");
7777
}
7878
}
79+
80+
this.afterUpdate();
7981
}
8082

8183
selectionItemsQuery() {

lib/ffdocs/view/javascript/search.js

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
class SearchInput {
22

33
constructor(elem) {
4+
this.prefetchLinks = new Set();
5+
46
elem.addEventListener("input", () => {
57
this.update(elem.value.trim().toLowerCase());
68
});
@@ -60,7 +62,7 @@ class SearchInput {
6062
}
6163

6264
moveSelection(direction) {
63-
let elems = document.querySelectorAll(this.selectionItemsQuery())
65+
let elems = document.querySelectorAll(this.selectionItemsQuery());
6466

6567
if(elems.length === 0) { return; }
6668

@@ -101,4 +103,37 @@ class SearchInput {
101103
url.searchParams.set("q", query);
102104
history.replaceState({}, "", url.href);
103105
}
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+
}
104139
}

0 commit comments

Comments
 (0)