-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
52 lines (42 loc) · 1.36 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { Plugin } from "$fresh/server.ts";
export interface Options {
prefetch?: 'all' | 'by-attribute'
};
const prefetch = ({ prefetch = 'all' }: Options): Plugin => {
const main = `data:application/javascript,export default function (state) {
if (window.requestIdleCallback) {
// prefetched links set
const prefetched = new Set();
// only prefetch relative links
const isRelativeUrl = (href) => typeof href === "string" && !/^http(s)?:\/\/|#/.test(href);
const createPrefetchLink = (href) => {
console.log('Prefetchig', href);
const linkTag = document.createElement('link');
linkTag.rel = 'prefetch';
linkTag.href = href;
linkTag.as = 'document';
document.head.appendChild(linkTag);
};
window.requestIdleCallback(() => {
document.querySelectorAll("${prefetch === 'all' ? "a" : "a[prefetch]"}").forEach((element) => {
const href = element.getAttribute("href");
if (isRelativeUrl(href) && prefetched.has(href) === false) {
prefetched.add(href);
createPrefetchLink(href);
}
})
});
}
}`
return {
name: 'prefetch',
entrypoints: { main },
render: (ctx) => {
ctx.render()
return {
scripts: [{ entrypoint: 'main', state: {} }]
}
}
}
}
export default prefetch