-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
81 lines (72 loc) · 2.28 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { Plugin } from "$fresh/server.ts";
export interface Options {
/** Attempt higher priority fetch (low or high) */
priority?: boolean;
/** Allowed origins to prefetch (empty allows all) */
origins?: string[];
/** Timeout after which prefetching will occur */
timeout?: number;
/**
* The concurrency limit for prefetching
* @default 10
*/
throttle?: number;
/** The area percentage of each link that must have entered the viewport to be fetched */
threshold?: number;
/** The total number of prefetches to allow */
limit?: number;
/** Time each link needs to stay inside viewport before prefetching (milliseconds) */
delay?: number;
/** Option to switch from prefetching and use prerendering only */
prerender?: boolean;
/** Option to use both prerendering and prefetching */
prerenderAndPrefetch?: boolean;
/**
* Strategy to prefetch.
*
* set opt-in to prefetch only anchor tags containing the data-prefetch attribute
* set opt-out to ignore only those links with the data-noprefetch attribute
* set aggresive to prefetch all links
*
* @default undefined
*/
strategy?: "opt-in" | "opt-out";
}
const prefetch = (options: Options = {
throttle: 10,
}): Plugin => {
const main = `data:application/javascript,
import { listen as qlListen } from "https://esm.sh/[email protected]";
function getOptions (options) {
if (options.strategy) {
options.ignores = [
...(options.ignores ?? []),
options.strategy === 'opt-in'
? (_uri, elem) => !elem.hasAttribute('data-prefetch')
: (_uri, elem) => elem.hasAttribute('data-noprefetch')
];
}
return options;
};
function listen (options) {
return qlListen(getOptions(options))
};
export default function(options) {
if (document.readyState === "complete" || document.readyState === "loaded" || document.readyState === "interactive") {
listen(options);
} else {
document.addEventListener("DOMContentLoaded", () => listen(options));
}
};`;
return {
name: "prefetch",
entrypoints: { main },
render: (ctx) => {
ctx.render();
return {
scripts: [{ entrypoint: "main", state: options }],
};
},
};
};
export default prefetch;