Updates prefetch integration to add "only prefetch link on hover/mouseover/focus" option (#6585)

* modifies prefetch to add the option to only prefetch certain pages on hover

* adds new pages to the test website to showcase prefetch-intent functionality

* adds tests to verify prefetch-intent behavior

* adds changelog

* waits until networkidle to check if the prefetching worked instead of waiting on a specific url load

* allows intentSelector to be either a string or array of strings

* Revert "allows intentSelector to be either a string or array of strings"

This reverts commit b0268eb0d5.

* fixes the multiple selector logic and adds tests

* updates docs to include new prefetch-intent integration

* Update packages/integrations/prefetch/README.md

Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>

* Update packages/integrations/prefetch/README.md

Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>

* Update packages/integrations/prefetch/README.md

Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>

* Update .changeset/little-cars-exist.md

Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>

* Update packages/integrations/prefetch/README.md

Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>

---------

Co-authored-by: Erika <3019731+Princesseuh@users.noreply.github.com>
Co-authored-by: Nate Moore <natemoo-re@users.noreply.github.com>
Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
Co-authored-by: Emanuele Stoppa <my.burning@gmail.com>
This commit is contained in:
Kory Smith 2023-07-07 16:01:23 -04:00 committed by GitHub
parent c135633bf6
commit 9807e4dc22
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 331 additions and 6 deletions

View file

@ -0,0 +1,5 @@
---
'@astrojs/prefetch': minor
---
Adds the option to prefetch a link only when it is hovered or focused.

View file

@ -56,6 +56,8 @@ export default defineConfig({
When you install the integration, the prefetch script is automatically added to every page in the project. Just add `rel="prefetch"` to any `<a />` links on your page and you're ready to go!
In addition, you can add `rel="prefetch-intent"` to any `<a />` links on your page to prefetch them only when they are hovered over, touched, or focused. This is especially useful to conserve data usage when viewing your site.
## Configuration
The Astro Prefetch integration handles which links on the site are prefetched and it has its own options. Change these in the `astro.config.mjs` file which is where your project's integration settings live.
@ -80,6 +82,28 @@ export default defineConfig({
});
```
### config.intentSelector
By default, the prefetch script also searches the page for any links that include a `rel="prefetch-intent"` attribute, ex: `<a rel="prefetch-intent" />`. This behavior can be changed in your `astro.config.*` file to use a custom query selector when finding prefetch-intent links.
__`astro.config.mjs`__
```js
import { defineConfig } from 'astro/config';
import prefetch from '@astrojs/prefetch';
export default defineConfig({
// ...
integrations: [prefetch({
// Only prefetch links with an href that begins with `/products` or `/coupons`
intentSelector: ["a[href^='/products']", "a[href^='/coupons']"]
// Use a string to prefetch a single selector
// intentSelector: "a[href^='/products']"
})],
});
```
### config.throttle
By default the prefetch script will only prefetch one link at a time. This behavior can be changed in your `astro.config.*` file to increase the limit for concurrent downloads.

View file

@ -77,11 +77,18 @@ export interface PrefetchOptions {
* @default 1
*/
throttle?: number;
/**
* Element selector used to find all links on the page that should be prefetched on user interaction.
*
* @default 'a[href][rel~="prefetch-intent"]'
*/
intentSelector?: string | string[];
}
export default function prefetch({
selector = 'a[href][rel~="prefetch"]',
throttle = 1,
intentSelector = 'a[href][rel~="prefetch-intent"]',
}: PrefetchOptions) {
// If the navigator is offline, it is very unlikely that a request can be made successfully
if (!navigator.onLine) {
@ -109,7 +116,21 @@ export default function prefetch({
new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting && entry.target instanceof HTMLAnchorElement) {
toAdd(() => preloadHref(entry.target as HTMLAnchorElement).finally(isDone));
const relAttributeValue = entry.target.getAttribute('rel') || '';
let matchesIntentSelector = false;
// Check if intentSelector is an array
if (Array.isArray(intentSelector)) {
// If intentSelector is an array, use .some() to check for matches
matchesIntentSelector = intentSelector.some((intent) =>
relAttributeValue.includes(intent)
);
} else {
// If intentSelector is a string, use .includes() to check for a match
matchesIntentSelector = relAttributeValue.includes(intentSelector);
}
if (!matchesIntentSelector) {
toAdd(() => preloadHref(entry.target as HTMLAnchorElement).finally(isDone));
}
}
});
});
@ -117,5 +138,18 @@ export default function prefetch({
requestIdleCallback(() => {
const links = [...document.querySelectorAll<HTMLAnchorElement>(selector)].filter(shouldPreload);
links.forEach(observe);
const intentSelectorFinal = Array.isArray(intentSelector)
? intentSelector.join(',')
: intentSelector;
// Observe links with prefetch-intent
const intentLinks = [
...document.querySelectorAll<HTMLAnchorElement>(intentSelectorFinal),
].filter(shouldPreload);
intentLinks.forEach((link) => {
events.map((event) =>
link.addEventListener(event, onLinkEvent, { passive: true, once: true })
);
});
});
}

View file

@ -37,18 +37,44 @@ test.describe('Basic prefetch', () => {
).toBeTruthy();
});
});
test.describe('prefetches rel="prefetch-intent" links only on hover', () => {
test('prefetches /uses on hover', async ({ page, astro }) => {
const requests = [];
page.on('request', (request) => requests.push(request.url()));
await page.goto(astro.resolveUrl('/'));
await page.waitForLoadState('networkidle');
expect(
requests.includes(astro.resolveUrl('/uses')),
'/uses was not prefetched'
).toBeFalsy();
await page.hover('a[href="/uses"]');
await page.waitForLoadState('networkidle');
expect(
requests.includes(astro.resolveUrl('/uses')),
'/uses was prefetched on hover'
).toBeTruthy();
});
});
});
test.describe('build', () => {
let previewServer;
test.beforeAll(async ({ astro }) => {
test.beforeEach(async ({ astro }) => {
await astro.build();
previewServer = await astro.preview();
});
// important: close preview server (free up port and connection)
test.afterAll(async () => {
test.afterEach(async () => {
await previewServer.stop();
});
@ -74,5 +100,31 @@ test.describe('Basic prefetch', () => {
).toBeTruthy();
});
});
test.describe('prefetches rel="prefetch-intent" links only on hover', () => {
test('prefetches /uses on hover', async ({ page, astro }) => {
const requests = [];
page.on('request', (request) => requests.push(request.url()));
await page.goto(astro.resolveUrl('/'));
await page.waitForLoadState('networkidle');
expect(
requests.includes(astro.resolveUrl('/uses')),
'/uses was not prefetched'
).toBeFalsy();
await page.hover('a[href="/uses"]');
await page.waitForLoadState('networkidle');
expect(
requests.includes(astro.resolveUrl('/uses')),
'/uses was prefetched on hover'
).toBeTruthy();
});
});
});
});

View file

@ -2,11 +2,19 @@ import { expect } from '@playwright/test';
import { testFactory } from './test-utils.js';
import prefetch from '../dist/index.js';
const customSelector = 'a[href="/contact"]';
const customIntentSelector = [
'a[href][rel~="custom-intent"]',
'a[href][rel~="customer-intent"]',
'a[href][rel~="customest-intent"]',
];
const test = testFactory({
root: './fixtures/basic-prefetch/',
integrations: [
prefetch({
selector: 'a[href="/contact"]',
selector: customSelector,
intentSelector: customIntentSelector,
}),
],
});
@ -50,13 +58,13 @@ test.describe('Custom prefetch selectors', () => {
test.describe('build', () => {
let previewServer;
test.beforeAll(async ({ astro }) => {
test.beforeEach(async ({ astro }) => {
await astro.build();
previewServer = await astro.preview();
});
// important: close preview server (free up port and connection)
test.afterAll(async () => {
test.afterEach(async () => {
await previewServer.stop();
});
@ -84,3 +92,167 @@ test.describe('Custom prefetch selectors', () => {
});
});
});
test.describe('Custom prefetch intent selectors', () => {
test.describe('dev', () => {
let devServer;
test.beforeEach(async ({ astro }) => {
devServer = await astro.startDevServer();
});
test.afterEach(async () => {
await devServer.stop();
});
test('prefetches custom intent links only on hover if provided an array', async ({
page,
astro,
}) => {
const requests = [];
page.on('request', (request) => requests.push(request.url()));
await page.goto(astro.resolveUrl('/'));
await page.waitForLoadState('networkidle');
expect(
requests.includes(astro.resolveUrl('/terms')),
'/terms was not prefetched initially'
).toBeFalsy();
expect(
requests.includes(astro.resolveUrl('/conditions')),
'/conditions was not prefetched initially'
).toBeFalsy();
const combinedIntentSelectors = customIntentSelector.join(',');
const intentElements = await page.$$(combinedIntentSelectors);
for (const element of intentElements) {
await element.hover();
}
await page.waitForLoadState('networkidle');
expect(
requests.includes(astro.resolveUrl('/terms')),
'/terms was prefetched on hover'
).toBeTruthy();
expect(
requests.includes(astro.resolveUrl('/conditions')),
'/conditions was prefetched on hover'
).toBeTruthy();
});
test('prefetches custom intent links only on hover if provided a string', async ({
page,
astro,
}) => {
const requests = [];
page.on('request', (request) => requests.push(request.url()));
await page.goto(astro.resolveUrl('/'));
await page.waitForLoadState('networkidle');
expect(
requests.includes(astro.resolveUrl('/terms')),
'/terms was not prefetched initially'
).toBeFalsy();
await page.hover(customIntentSelector[0]);
await page.waitForLoadState('networkidle');
expect(
requests.includes(astro.resolveUrl('/terms')),
'/terms was prefetched on hover'
).toBeTruthy();
});
});
test.describe('build', () => {
let previewServer;
test.beforeEach(async ({ astro }) => {
await astro.build();
previewServer = await astro.preview();
});
// important: close preview server (free up port and connection)
test.afterEach(async () => {
await previewServer.stop();
});
test('prefetches custom intent links only on hover if provided an array', async ({
page,
astro,
}) => {
const requests = [];
page.on('request', (request) => requests.push(request.url()));
await page.goto(astro.resolveUrl('/'));
await page.waitForLoadState('networkidle');
expect(
requests.includes(astro.resolveUrl('/terms')),
'/terms was not prefetched initially'
).toBeFalsy();
expect(
requests.includes(astro.resolveUrl('/conditions')),
'/conditions was not prefetched initially'
).toBeFalsy();
const combinedIntentSelectors = customIntentSelector.join(',');
const intentElements = await page.$$(combinedIntentSelectors);
for (const element of intentElements) {
await element.hover();
}
await page.waitForLoadState('networkidle');
expect(
requests.includes(astro.resolveUrl('/terms')),
'/terms was prefetched on hover'
).toBeTruthy();
expect(
requests.includes(astro.resolveUrl('/conditions')),
'/conditions was prefetched on hover'
).toBeTruthy();
});
test('prefetches custom intent links only on hover if provided a string', async ({
page,
astro,
}) => {
const requests = [];
page.on('request', (request) => requests.push(request.url()));
await page.goto(astro.resolveUrl('/'));
await page.waitForLoadState('networkidle');
expect(
requests.includes(astro.resolveUrl('/terms')),
'/terms was not prefetched initially'
).toBeFalsy();
await page.hover(customIntentSelector[0]);
await page.waitForLoadState('networkidle');
expect(
requests.includes(astro.resolveUrl('/terms')),
'/terms was prefetched on hover'
).toBeTruthy();
});
});
});

View file

@ -0,0 +1,11 @@
---
---
<html>
<head>
<title>Conditions</title>
</head>
<body>
<h1>Conditions</h1>
</body>
</html>

View file

@ -19,11 +19,16 @@
<li>
<a href="/admin">Admin</a>
</li>
<li>
<a href="/uses" rel="prefetch-intent">Uses</a>
</li>
</ul>
</nav>
<footer>
<a href="/contact" rel="prefetch">Contact</a>
<a href="/terms" rel="custom-intent">Terms</a>
<a href="/conditions" rel="customer-intent">Terms</a>
</footer>
</body>
</html>

View file

@ -0,0 +1,11 @@
---
---
<html>
<head>
<title>Terms</title>
</head>
<body>
<h1>Terms</h1>
</body>
</html>

View file

@ -0,0 +1,11 @@
---
---
<html>
<head>
<title>Uses</title>
</head>
<body>
<h1>Uses</h1>
</body>
</html>