Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add experimental client prerender #9644

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1566,6 +1566,21 @@ export interface AstroUserConfig {
* ```
*/
contentCollectionCache?: boolean;

/**
* @docs
* @name experimental.clientPrerender
* @type {boolean}
* @default `false`
rossrobino marked this conversation as resolved.
Show resolved Hide resolved
* @description
* Progressive enhancement to use the experimental Speculation Rules API
* when supported to prerender on the client. Use this setting to prerender the
* page on the client, including running client side JavaScript
* (see [unsafe prefetching](https://developer.mozilla.org/en-US/docs/Web/API/Speculation_Rules_API#unsafe_prefetching)).
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Speculation_Rules_API)
rossrobino marked this conversation as resolved.
Show resolved Hide resolved
*/
clientPrerender?: boolean;
};
}

Expand Down
5 changes: 5 additions & 0 deletions packages/astro/src/core/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ const ASTRO_CONFIG_DEFAULTS = {
experimental: {
optimizeHoistedScript: false,
contentCollectionCache: false,
clientPrerender: false,
},
} satisfies AstroUserConfig & { server: { open: boolean } };

Expand Down Expand Up @@ -393,6 +394,10 @@ export const AstroConfigSchema = z.object({
.boolean()
.optional()
.default(ASTRO_CONFIG_DEFAULTS.experimental.contentCollectionCache),
clientPrerender: z
.boolean()
.optional()
.default(ASTRO_CONFIG_DEFAULTS.experimental.clientPrerender),
})
.strict(
`Invalid or outdated experimental feature.\nCheck for incorrect spelling or outdated Astro version.\nSee https://docs.astro.build/en/reference/configuration-reference/#experimental-flags for a list of all current experiments.`
Expand Down
34 changes: 33 additions & 1 deletion packages/astro/src/prefetch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ const listenedAnchors = new WeakSet<HTMLAnchorElement>();
let prefetchAll: boolean = __PREFETCH_PREFETCH_ALL__;
// @ts-expect-error injected global
let defaultStrategy: string = __PREFETCH_DEFAULT_STRATEGY__;
// @ts-expect-error injected global
let clientPrerender: boolean = __EXPERIMENTAL_CLIENT_PRERENDER__;

interface InitOptions {
defaultStrategy?: string;
Expand Down Expand Up @@ -216,7 +218,14 @@ export function prefetch(url: string, opts?: PrefetchOptions) {
const priority = opts?.with ?? 'link';
debug?.(`[astro] Prefetching ${url} with ${priority}`);

if (priority === 'link') {
if (
clientPrerender &&
HTMLScriptElement.supports &&
HTMLScriptElement.supports('speculationrules')
) {
// this code is tree-shaken if unused
appendSpeculationRules(url);
Comment on lines +221 to +227
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe in the future we can use prerender/prefetch when using with: 'link' or with: 'fetch' respectively. That way links that enter the viewport don't get prerendered entirely. But we can improve this later if needed.

} else if (priority === 'link') {
const link = document.createElement('link');
link.rel = 'prefetch';
link.setAttribute('href', url);
Expand Down Expand Up @@ -301,3 +310,26 @@ function onPageLoad(cb: () => void) {
cb();
});
}

/**
* Appends a `<script type="speculationRules">` tag to the head of the
rossrobino marked this conversation as resolved.
Show resolved Hide resolved
* document that prerenders the `url` passed in.
*
* Modifying the script and appending a new link does not trigger the prerender.
* A new script must be added for each `url`.
*
* @param url The url of the page to prerender.
*/
function appendSpeculationRules(url: string) {
const script = document.createElement('script');
script.type = 'speculationrules';
script.textContent = JSON.stringify({
prerender: [
{
source: 'list',
urls: [url],
},
],
});
document.head.append(script);
}
6 changes: 5 additions & 1 deletion packages/astro/src/prefetch/vite-plugin-prefetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ export default function astroPrefetch({ settings }: { settings: AstroSettings })
if (id.includes(prefetchInternalModuleFsSubpath)) {
return code
.replace('__PREFETCH_PREFETCH_ALL__', JSON.stringify(prefetch?.prefetchAll))
.replace('__PREFETCH_DEFAULT_STRATEGY__', JSON.stringify(prefetch?.defaultStrategy));
.replace('__PREFETCH_DEFAULT_STRATEGY__', JSON.stringify(prefetch?.defaultStrategy))
.replace(
'__EXPERIMENTAL_CLIENT_PRERENDER__',
JSON.stringify(settings.config.experimental.clientPrerender)
);
}
},
};
Expand Down