0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-01-06 22:10:10 -05:00

allows intentSelector to be either a string or array of strings

This commit is contained in:
Kory Smith 2023-03-24 17:16:16 -04:00
parent b4afcae5a4
commit b0268eb0d5

View file

@ -64,6 +64,17 @@ async function preloadHref(link: HTMLAnchorElement) {
} catch {} } catch {}
} }
function isIntentSelector(link: HTMLAnchorElement, intentSelector: string | string[]) {
if (Array.isArray(intentSelector)) {
return intentSelector.some((selector) => link.matches(selector));
}
return link.matches(intentSelector);
}
function observeIntent(link: HTMLAnchorElement) {
events.map((event) => link.addEventListener(event, onLinkEvent, { passive: true, once: true }));
}
export interface PrefetchOptions { export interface PrefetchOptions {
/** /**
* Element selector used to find all links on the page that should be prefetched. * Element selector used to find all links on the page that should be prefetched.
@ -82,7 +93,7 @@ export interface PrefetchOptions {
* *
* @default 'a[href][rel~="prefetch-intent"]' * @default 'a[href][rel~="prefetch-intent"]'
*/ */
intentSelector?: string; intentSelector?: string | string[];
} }
export default function prefetch({ export default function prefetch({
@ -116,7 +127,7 @@ export default function prefetch({
new IntersectionObserver((entries) => { new IntersectionObserver((entries) => {
entries.forEach((entry) => { entries.forEach((entry) => {
if (entry.isIntersecting && entry.target instanceof HTMLAnchorElement) { if (entry.isIntersecting && entry.target instanceof HTMLAnchorElement) {
if (entry.target.getAttribute('rel')?.indexOf(intentSelector) === -1) { if (!isIntentSelector(entry.target, intentSelector)) {
toAdd(() => preloadHref(entry.target as HTMLAnchorElement).finally(isDone)); toAdd(() => preloadHref(entry.target as HTMLAnchorElement).finally(isDone));
} }
} }
@ -125,16 +136,12 @@ export default function prefetch({
requestIdleCallback(() => { requestIdleCallback(() => {
const links = [...document.querySelectorAll<HTMLAnchorElement>(selector)].filter(shouldPreload); const links = [...document.querySelectorAll<HTMLAnchorElement>(selector)].filter(shouldPreload);
links.forEach(observe); links.forEach((link) => {
if (isIntentSelector(link, intentSelector)) {
// Observe links with prefetch-intent observeIntent(link);
const intentLinks = [...document.querySelectorAll<HTMLAnchorElement>(intentSelector)].filter( } else {
shouldPreload observe(link);
); }
intentLinks.forEach((link) => {
events.map((event) =>
link.addEventListener(event, onLinkEvent, { passive: true, once: true })
);
}); });
}); });
} }