summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar Kory Smith <kor54e@gmail.com> 2023-07-07 16:01:23 -0400
committerGravatar GitHub <noreply@github.com> 2023-07-07 16:01:23 -0400
commit9807e4dc22355f0b3b2ff65b0724a95af8e9702d (patch)
tree723c86670761f97a1bc7b89141521a740e37aff8
parentc135633bf6a84e751249920cba9009f0e394e29a (diff)
downloadastro-9807e4dc22355f0b3b2ff65b0724a95af8e9702d.tar.gz
astro-9807e4dc22355f0b3b2ff65b0724a95af8e9702d.tar.zst
astro-9807e4dc22355f0b3b2ff65b0724a95af8e9702d.zip
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 b0268eb0d5220ad2b08b0b7aee23f43e4caf879f. * 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>
-rw-r--r--.changeset/little-cars-exist.md5
-rw-r--r--packages/integrations/prefetch/README.md24
-rw-r--r--packages/integrations/prefetch/src/client.ts36
-rw-r--r--packages/integrations/prefetch/test/basic-prefetch.test.js56
-rw-r--r--packages/integrations/prefetch/test/custom-selectors.test.js178
-rw-r--r--packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/conditions.astro11
-rw-r--r--packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/index.astro5
-rw-r--r--packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/terms.astro11
-rw-r--r--packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/uses.astro11
9 files changed, 331 insertions, 6 deletions
diff --git a/.changeset/little-cars-exist.md b/.changeset/little-cars-exist.md
new file mode 100644
index 000000000..50475a7fb
--- /dev/null
+++ b/.changeset/little-cars-exist.md
@@ -0,0 +1,5 @@
+---
+'@astrojs/prefetch': minor
+---
+
+Adds the option to prefetch a link only when it is hovered or focused.
diff --git a/packages/integrations/prefetch/README.md b/packages/integrations/prefetch/README.md
index 4dab2121b..9a061fc2a 100644
--- a/packages/integrations/prefetch/README.md
+++ b/packages/integrations/prefetch/README.md
@@ -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.
diff --git a/packages/integrations/prefetch/src/client.ts b/packages/integrations/prefetch/src/client.ts
index a8b88d85c..dc05cb84b 100644
--- a/packages/integrations/prefetch/src/client.ts
+++ b/packages/integrations/prefetch/src/client.ts
@@ -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 })
+ );
+ });
});
}
diff --git a/packages/integrations/prefetch/test/basic-prefetch.test.js b/packages/integrations/prefetch/test/basic-prefetch.test.js
index 6bab8a478..5fab536aa 100644
--- a/packages/integrations/prefetch/test/basic-prefetch.test.js
+++ b/packages/integrations/prefetch/test/basic-prefetch.test.js
@@ -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();
+ });
+ });
});
});
diff --git a/packages/integrations/prefetch/test/custom-selectors.test.js b/packages/integrations/prefetch/test/custom-selectors.test.js
index 803e1dc3b..ac15d7d5f 100644
--- a/packages/integrations/prefetch/test/custom-selectors.test.js
+++ b/packages/integrations/prefetch/test/custom-selectors.test.js
@@ -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();
+ });
+ });
+});
diff --git a/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/conditions.astro b/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/conditions.astro
new file mode 100644
index 000000000..345abaa38
--- /dev/null
+++ b/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/conditions.astro
@@ -0,0 +1,11 @@
+---
+---
+
+<html>
+<head>
+<title>Conditions</title>
+</head>
+<body>
+ <h1>Conditions</h1>
+</body>
+</html>
diff --git a/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/index.astro b/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/index.astro
index 58a864552..b78e39553 100644
--- a/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/index.astro
+++ b/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/index.astro
@@ -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>
diff --git a/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/terms.astro b/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/terms.astro
new file mode 100644
index 000000000..a0fcc1004
--- /dev/null
+++ b/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/terms.astro
@@ -0,0 +1,11 @@
+---
+---
+
+<html>
+<head>
+<title>Terms</title>
+</head>
+<body>
+ <h1>Terms</h1>
+</body>
+</html>
diff --git a/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/uses.astro b/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/uses.astro
new file mode 100644
index 000000000..15b050061
--- /dev/null
+++ b/packages/integrations/prefetch/test/fixtures/basic-prefetch/src/pages/uses.astro
@@ -0,0 +1,11 @@
+---
+---
+
+<html>
+<head>
+<title>Uses</title>
+</head>
+<body>
+ <h1>Uses</h1>
+</body>
+</html>