Skip to content

Commit ce0aa40

Browse files
committed
Adds index: initial implementation
1 parent fd6149b commit ce0aa40

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

index.mjs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
*
3+
* @param urls Array of URLs to prefetch
4+
*/
5+
function fetchLinks(urls) {
6+
urls.forEach((url) => {
7+
prefetch(url);
8+
});
9+
}
10+
11+
/**
12+
* Extract only links that are in the visible viewport
13+
* @param el DOM element to check for in-viewport links
14+
*/
15+
function extractInViewportLinks(el) {
16+
return new Promise((resolve, reject) => {
17+
const urls = [];
18+
const links = el.querySelectorAll('a');
19+
const observer = new IntersectionObserver(entries => {
20+
entries.forEach(entry => {
21+
// Link is in the view
22+
if (entry.intersectionRatio > 0) {
23+
urls.push(entry.target.href);
24+
} else {
25+
// Link is out of the view
26+
}
27+
});
28+
resolve(urls);
29+
});
30+
links.forEach(link => {
31+
observer.observe(link);
32+
});
33+
});
34+
}
35+
36+
/**
37+
*
38+
* @param options
39+
* options.urls: Array of URLs to prefetch (override)
40+
* options.el: DOM element to prefetch in-viewport links of
41+
*/
42+
export default function quicklink(options) {
43+
options = options || {};
44+
requestIdleCallback(() => {
45+
// Prefetch an array of URLs if supplied (as an override)
46+
if (options.urls !== undefined && options.urls.length > 0) {
47+
fetchLinks(options.urls);
48+
} else {
49+
// Element to extract in-viewport links for
50+
let el = options.el || document;
51+
extractInViewportLinks(el).then((urls) => {
52+
fetchLinks(urls);
53+
});
54+
}
55+
});
56+
}

0 commit comments

Comments
 (0)