Skip to content

Commit

Permalink
Updates prefetch integration to add "only prefetch link on hover/mous…
Browse files Browse the repository at this point in the history
…eover/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 b0268eb.

* 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>
  • Loading branch information
5 people committed Jul 7, 2023
1 parent c135633 commit 9807e4d
Show file tree
Hide file tree
Showing 9 changed files with 331 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/little-cars-exist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/prefetch': minor
---

Adds the option to prefetch a link only when it is hovered or focused.
24 changes: 24 additions & 0 deletions packages/integrations/prefetch/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down
36 changes: 35 additions & 1 deletion packages/integrations/prefetch/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -109,13 +116,40 @@ 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));
}
}
});
});

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 })
);
});
});
}
56 changes: 54 additions & 2 deletions packages/integrations/prefetch/test/basic-prefetch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});

Expand All @@ -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();
});
});
});
});
178 changes: 175 additions & 3 deletions packages/integrations/prefetch/test/custom-selectors.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}),
],
});
Expand Down Expand Up @@ -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();
});

Expand Down Expand Up @@ -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();
});
});
});

0 comments on commit 9807e4d

Please sign in to comment.