diff --git a/docs/1.configuration.md b/docs/1.configuration.md index eb82da287..2d6465c8c 100644 --- a/docs/1.configuration.md +++ b/docs/1.configuration.md @@ -25,6 +25,24 @@ export default defineNuxtConfig({ }) ``` +## `preconnect` + +Nuxt Image can add a [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel/preconnect) hint to the page head for the origins of the images rendered on the server. This lets the browser start the DNS, TCP and TLS handshake with your image provider before the images are parsed. + +Preconnecting is opt-in: enable it per image with the [`preconnect` prop](/modules/image/usage/nuxt-img#preconnect), or for every image by setting `preconnect` to `true` in your configuration. + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + image: { + preconnect: true + } +}) +``` + +Only external `http(s)` origins are preconnected — relative and same-origin images (for example the default `ipx` provider) are ignored. Images from the same origin and connection mode (`crossorigin`) share a single hint. + +Enable preconnecting for the images that appear above the fold. Every hint starts a connection, so browsers and Lighthouse recommend keeping the number of preconnected origins small. + ## `quality` The quality for the generated image(s). diff --git a/docs/2.usage/1.nuxt-img.md b/docs/2.usage/1.nuxt-img.md index 720074e23..38095921b 100644 --- a/docs/2.usage/1.nuxt-img.md +++ b/docs/2.usage/1.nuxt-img.md @@ -376,6 +376,22 @@ Accepted values are `auto`, `high`, or `low`. ``` +### `preconnect` + +Adds a [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel/preconnect) hint for the origin of the image that is rendered on the server, so the browser can start the DNS, TCP and TLS handshake with your image provider before the image is parsed. + +```vue + +``` + +Only external `http(s)` origins produce a hint — relative and same-origin images (for example the default `ipx` provider) are ignored, and images sharing an origin and `crossorigin` mode share a single hint. When a [`placeholder`](#placeholder) is rendered, the hint follows the placeholder URL, as that is the image the browser fetches first. + +Preconnecting is disabled by default. Enable it for images that appear above the fold rather than every image on the page, since each hint starts a connection. To enable it for every image, set [`preconnect`](/modules/image/configuration#preconnect) in your configuration. + ### `loading` This is a [native](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/loading) attribute that provides a hint diff --git a/docs/2.usage/2.nuxt-picture.md b/docs/2.usage/2.nuxt-picture.md index 78258a5b8..364d29fa4 100644 --- a/docs/2.usage/2.nuxt-picture.md +++ b/docs/2.usage/2.nuxt-picture.md @@ -18,6 +18,8 @@ Learn more about the [`` tag on MDN](https://developer.mozilla.org/en-U Unlike the native [`` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture), `` currently doesn't support using multiple image sources. See [#309](https://github.com/nuxt/image/issues/309) for more info. :: +**Note:** Like ``, `` can preconnect to the origins of its external image sources during server rendering. Pass the [`preconnect` prop](/modules/image/usage/nuxt-img#preconnect) to opt in. + ## Props ::tip diff --git a/playground/app/pages/img-preload.vue b/playground/app/pages/img-preload.vue index bfe7b66a3..1cd165f4f 100644 --- a/playground/app/pages/img-preload.vue +++ b/playground/app/pages/img-preload.vue @@ -7,6 +7,7 @@ height="500" densities="x1" preload + preconnect />

Preload with densities and no sizes prop

Preload with densities and sizes prop

@@ -25,6 +27,7 @@ sizes="100vw md:500px" densities="x1 x2" preload + preconnect />

Preload with densities, sizes prop and default fetch priority high

@@ -35,6 +38,7 @@ sizes="100vw md:500px" densities="x1 x2" :preload="{ fetchPriority: 'high' }" + preconnect /> diff --git a/playground/app/pages/picture-preconnect.vue b/playground/app/pages/picture-preconnect.vue new file mode 100644 index 000000000..91d51ae46 --- /dev/null +++ b/playground/app/pages/picture-preconnect.vue @@ -0,0 +1,11 @@ + diff --git a/playground/app/pages/preconnect-crossorigin-picture.vue b/playground/app/pages/preconnect-crossorigin-picture.vue new file mode 100644 index 000000000..f3b604e3b --- /dev/null +++ b/playground/app/pages/preconnect-crossorigin-picture.vue @@ -0,0 +1,20 @@ + diff --git a/playground/app/pages/preconnect-crossorigin.vue b/playground/app/pages/preconnect-crossorigin.vue new file mode 100644 index 000000000..42b8566ee --- /dev/null +++ b/playground/app/pages/preconnect-crossorigin.vue @@ -0,0 +1,27 @@ + diff --git a/playground/app/pages/preconnect-disabled.vue b/playground/app/pages/preconnect-disabled.vue new file mode 100644 index 000000000..c2c9f3296 --- /dev/null +++ b/playground/app/pages/preconnect-disabled.vue @@ -0,0 +1,12 @@ + diff --git a/playground/app/pages/preconnect-ignored.vue b/playground/app/pages/preconnect-ignored.vue new file mode 100644 index 000000000..61c33f650 --- /dev/null +++ b/playground/app/pages/preconnect-ignored.vue @@ -0,0 +1,26 @@ + diff --git a/playground/app/pages/preconnect-opt-out.vue b/playground/app/pages/preconnect-opt-out.vue new file mode 100644 index 000000000..bdc2d630b --- /dev/null +++ b/playground/app/pages/preconnect-opt-out.vue @@ -0,0 +1,11 @@ + diff --git a/playground/app/pages/preconnect-placeholder.vue b/playground/app/pages/preconnect-placeholder.vue new file mode 100644 index 000000000..d0a2dd2f0 --- /dev/null +++ b/playground/app/pages/preconnect-placeholder.vue @@ -0,0 +1,11 @@ + diff --git a/playground/app/pages/preconnect-protocol-relative.vue b/playground/app/pages/preconnect-protocol-relative.vue new file mode 100644 index 000000000..9243124ef --- /dev/null +++ b/playground/app/pages/preconnect-protocol-relative.vue @@ -0,0 +1,26 @@ + diff --git a/playground/app/pages/provider/[provider].vue b/playground/app/pages/provider/[provider].vue index eaf6d8dea..e8ae01dae 100644 --- a/playground/app/pages/provider/[provider].vue +++ b/playground/app/pages/provider/[provider].vue @@ -12,6 +12,7 @@ :provider="provider.name as any" v-bind="sample" :preload="{ fetchPriority: 'auto' }" + preconnect />
{{ sample }}
diff --git a/src/module.ts b/src/module.ts index cae1f73f0..000954d01 100644 --- a/src/module.ts +++ b/src/module.ts @@ -20,6 +20,7 @@ export interface ModuleOptions extends ImageProviders { densities: number[] format: CreateImageOptions['format'] quality?: CreateImageOptions['quality'] + preconnect: boolean } export * from './types' @@ -45,6 +46,7 @@ export default defineNuxtModule({ providers: {}, alias: {}, densities: [1, 2], + preconnect: false, }), meta: { name: '@nuxt/image', @@ -113,6 +115,7 @@ export default defineNuxtModule({ 'densities', 'format', 'quality', + 'preconnect', ]) const providers = await resolveProviders(nuxt, options) diff --git a/src/runtime/components/NuxtImg.vue b/src/runtime/components/NuxtImg.vue index d498adbe2..b3929e7f4 100644 --- a/src/runtime/components/NuxtImg.vue +++ b/src/runtime/components/NuxtImg.vue @@ -21,6 +21,7 @@ import { computed, onMounted, ref, useAttrs, useTemplateRef } from 'vue' import type { ImgHTMLAttributes } from 'vue' import { useImage } from '../composables' +import { addPreconnect } from '../utils/preconnect' import { prerenderStaticImages } from '../utils/prerender' import { markFeatureUsage } from '../utils/performance' import { useImageProps } from '../utils/props' @@ -35,7 +36,8 @@ export interface ImageProps ext placeholderClass?: string } -const props = defineProps>() +// `undefined` lets the global `image.preconnect` option apply +const props = withDefaults(defineProps>(), { preconnect: undefined }) const emit = defineEmits<{ (event: 'load', payload: Event): unknown @@ -103,6 +105,11 @@ const mainSrc = computed(() => const src = computed(() => placeholder.value || mainSrc.value) +if (import.meta.server && (props.preconnect ?? $img.options.preconnect)) { + // use the rendered URL: reading `mainSrc` forces `getSizes` during SSR with a placeholder + addPreconnect([src.value], { crossorigin: normalizedAttrs.value.crossorigin }) +} + if (import.meta.server && props.preload) { const hasMultipleDensities = sizes.value.srcset.includes('x, ') const isResponsive = hasMultipleDensities || !!sizes.value.sizes diff --git a/src/runtime/components/NuxtPicture.vue b/src/runtime/components/NuxtPicture.vue index eb82f407c..a5db2a818 100644 --- a/src/runtime/components/NuxtPicture.vue +++ b/src/runtime/components/NuxtPicture.vue @@ -30,6 +30,7 @@ import { computed, onMounted, useAttrs, useTemplateRef } from 'vue' import { prerenderStaticImages } from '../utils/prerender' import { markFeatureUsage } from '../utils/performance' import { useImage } from '../composables' +import { addPreconnect, type PreconnectOptions } from '../utils/preconnect' import { useImageProps } from '../utils/props' import type { BaseImageProps } from '../utils/props' import type { DataAttributes } from '../types' @@ -44,7 +45,8 @@ export interface PictureProps e defineOptions({ inheritAttrs: false }) -const props = defineProps>() +// `undefined` lets the global `image.preconnect` option apply +const props = withDefaults(defineProps>(), { preconnect: undefined }) const emit = defineEmits<{ (event: 'load', payload: Event): unknown @@ -119,6 +121,12 @@ const sources = computed(() => { }) }) +if (import.meta.server && (props.preconnect ?? $img.options.preconnect)) { + // `imgAttrs` is merged into `attrs.img` after the prop, so use that same value + const crossorigin = attrs.value.img.crossorigin as PreconnectOptions['crossorigin'] + addPreconnect(sources.value.map(source => source.src), { crossorigin }) +} + if (import.meta.server && props.preload) { useHead({ link: () => { const firstSource = sources.value[0] diff --git a/src/runtime/utils/preconnect.ts b/src/runtime/utils/preconnect.ts new file mode 100644 index 000000000..26ea14e52 --- /dev/null +++ b/src/runtime/utils/preconnect.ts @@ -0,0 +1,94 @@ +import { useHead, useRequestURL } from '#imports' + +/** Resolves the origin to preconnect to, or `undefined` for empty, relative, same-origin, unparseable or non-http(s) URLs. */ +function resolvePreconnectOrigin(url: string | undefined, baseHref: string): string | undefined { + if (!url) { + return + } + + let base: URL + let resolved: URL + try { + base = new URL(baseHref) + resolved = new URL(url, base) + } + catch { + return + } + + // keep protocol-relative urls scheme-less: prerendering runs over http, but the browser must pick the page's protocol + if (url.startsWith('//')) { + // URL drops a port that is default for the base protocol, which may not be default for the page's + const explicitPort = /^\/\/[^/?#]*:(\d+)(?=[/?#]|$)/.exec(url)?.[1] + const host = explicitPort && !resolved.port ? `${resolved.host}:${explicitPort}` : resolved.host + + return resolved.host === base.host ? undefined : `//${host}` + } + + if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') { + return + } + + if (resolved.origin === base.origin) { + return + } + + return resolved.origin +} + +/** + * @internal + */ +export interface PreconnectOptions { + crossorigin?: 'anonymous' | 'use-credentials' | '' | boolean +} + +/** + * Registers `` hints for image origins in one `useHead` call. + * + * @internal + */ +export const addPreconnect = (urls: Array, options: PreconnectOptions = {}): void => { + if (import.meta.client) { + return + } + + let base: string + try { + base = useRequestURL().href + } + catch { + return + } + + // an empty crossorigin attribute means "anonymous", same as `true` + const crossorigin: 'anonymous' | 'use-credentials' | undefined = options.crossorigin === true || options.crossorigin === '' + ? 'anonymous' + : (options.crossorigin || undefined) + + const links = new Map() + for (const url of urls) { + const origin = resolvePreconnectOrigin(url, base) + if (!origin) { + continue + } + + const key = `preconnect:${origin}${crossorigin ? `:${crossorigin}` : ''}` + if (links.has(key)) { + continue + } + + links.set(key, { + rel: 'preconnect', + href: origin, + key, + ...(crossorigin ? { crossorigin } : {}), + }) + } + + if (!links.size) { + return + } + + useHead({ link: [...links.values()] }) +} diff --git a/src/runtime/utils/props.ts b/src/runtime/utils/props.ts index dee657590..99f276c94 100644 --- a/src/runtime/utils/props.ts +++ b/src/runtime/utils/props.ts @@ -23,6 +23,7 @@ export interface BaseImageProps sizes?: string | Record densities?: string preload?: boolean | { fetchPriority: 'auto' | 'high' | 'low' } + preconnect?: boolean // attributes width?: string | number diff --git a/src/types/image.ts b/src/types/image.ts index d2db53b17..402ea2467 100644 --- a/src/types/image.ts +++ b/src/types/image.ts @@ -63,6 +63,7 @@ export interface CreateImageOptions { densities: number[] format: string[] quality?: number + preconnect?: boolean runtimeConfig: RuntimeConfig } diff --git a/test/e2e/generate.test.ts b/test/e2e/generate.test.ts index 4bb300721..0561c6d33 100644 --- a/test/e2e/generate.test.ts +++ b/test/e2e/generate.test.ts @@ -1,7 +1,7 @@ import { fileURLToPath } from 'node:url' import { describe, it, expect } from 'vitest' -import { setup, useTestContext } from '@nuxt/test-utils' +import { $fetch, setup, useTestContext } from '@nuxt/test-utils' import { useNuxt } from '@nuxt/kit' import { resolve } from 'pathe' import { glob } from 'tinyglobby' @@ -12,6 +12,7 @@ await setup({ nuxtConfig: { image: { inject: false, + preconnect: true, }, nitro: { prerender: { @@ -51,3 +52,20 @@ describe('ipx provider', () => { `) }) }) + +describe('preconnect', () => { + it('preconnects when enabled with the global image option', async () => { + // `/preconnect-opt-out` renders a cross-origin image without the `preconnect` prop + const html = await $fetch('/preconnect-opt-out') + + expect(html).toContain('href="https://res.cloudinary.com"') + expect(html).toContain('rel="preconnect"') + }) + + it('lets the prop disable the global image option', async () => { + const html = await $fetch('/preconnect-disabled') + + expect(html).toContain('https://res.cloudinary.com') + expect(html).not.toContain('rel="preconnect"') + }) +}) diff --git a/test/e2e/ssr.test.ts b/test/e2e/ssr.test.ts index 8e2a335f7..c5288e729 100644 --- a/test/e2e/ssr.test.ts +++ b/test/e2e/ssr.test.ts @@ -119,4 +119,132 @@ describe('browser (ssr: true)', () => { } `) }) + + it('does not preconnect unless the image opts in', async () => { + const page = await createPage() + await page.goto(url('/preconnect-opt-out')) + await page.waitForSelector('img') + + const origins = await page.$$eval('head link[rel="preconnect"]', links => links.map(link => link.getAttribute('href'))) + + expect(origins).toEqual([]) + + await page.close() + }) + + it('preconnects to a remote provider origin', async () => { + const page = await createPage() + await page.goto(url('/provider/cloudinary')) + await page.waitForSelector('img') + + const origins = await page.$$eval('head link[rel="preconnect"]', links => links.map(link => link.getAttribute('href'))) + + expect(origins).toContain('https://res.cloudinary.com') + expect(origins.filter(origin => origin === 'https://res.cloudinary.com')).toHaveLength(1) + + await page.close() + }) + + it('does not preconnect for same-origin images', async () => { + const page = await createPage() + await page.goto(url('/img-preload')) + await page.waitForSelector('img') + + const origins = await page.$$eval('head link[rel="preconnect"]', links => links.map(link => link.getAttribute('href'))) + + expect(origins).toEqual([]) + + await page.close() + }) + + it('preconnects for a remote provider rendered by NuxtPicture', async () => { + const page = await createPage() + await page.goto(url('/picture-preconnect')) + await page.waitForSelector('img') + + const origins = await page.$$eval('head link[rel="preconnect"]', links => links.map(link => link.getAttribute('href'))) + + expect(origins).toContain('https://res.cloudinary.com') + + await page.close() + }) + + it('mirrors crossorigin on the preconnect hint and keeps connection modes distinct', async () => { + const page = await createPage() + await page.goto(url('/preconnect-crossorigin')) + await page.waitForSelector('img') + + const hints = await page.$$eval('head link[rel="preconnect"]', links => links.map(link => ({ + href: link.getAttribute('href'), + crossorigin: link.getAttribute('crossorigin'), + }))) + + // Three images share one origin, but only two connection modes were requested + expect(hints).toHaveLength(2) + expect(hints).toContainEqual({ href: 'https://res.cloudinary.com', crossorigin: 'anonymous' }) + expect(hints).toContainEqual({ href: 'https://res.cloudinary.com', crossorigin: null }) + + await page.close() + }) + + it('preconnects to a remote placeholder origin', async () => { + const page = await createPage() + // the placeholder is the rendered `src`, so only its origin should be hinted + await page.goto(url('/preconnect-placeholder'), { waitUntil: 'domcontentloaded' }) + + const origins = await page.$$eval('head link[rel="preconnect"]', links => links.map(link => link.getAttribute('href'))) + + expect(origins).toEqual(['https://res.cloudinary.com']) + + await page.close() + }) + + it('ignores data, non-http(s) and same-origin sources', async () => { + const page = await createPage() + await page.goto(url('/preconnect-ignored'), { waitUntil: 'domcontentloaded' }) + await page.waitForSelector('img') + + const origins = await page.$$eval('head link[rel="preconnect"]', links => links.map(link => link.getAttribute('href'))) + + expect(origins).toEqual([]) + + await page.close() + }) + + it('keeps protocol-relative hints distinct from explicit http origins', async () => { + const page = await createPage() + await page.goto(url('/preconnect-protocol-relative'), { waitUntil: 'domcontentloaded' }) + + const hints = await page.$$eval('head link[rel="preconnect"]', links => links.map(link => ({ + href: link.getAttribute('href'), + hid: link.getAttribute('data-hid'), + }))) + + expect(hints).toHaveLength(3) + expect(hints).toContainEqual({ href: '//res.cloudinary.com', hid: 'preconnect://res.cloudinary.com' }) + expect(hints).toContainEqual({ href: 'http://res.cloudinary.com', hid: 'preconnect:http://res.cloudinary.com' }) + // an explicit port default for http is still not default for the https page that may serve it + expect(hints).toContainEqual({ href: '//res.cloudinary.com:80', hid: 'preconnect://res.cloudinary.com:80' }) + + await page.close() + }) + + it('matches the picture preconnect hint to the crossorigin the image renders', async () => { + const page = await createPage() + await page.goto(url('/preconnect-crossorigin-picture'), { waitUntil: 'domcontentloaded' }) + + const rendered = await page.$$eval('picture img', imgs => imgs.map(img => img.getAttribute('crossorigin'))) + const hints = await page.$$eval('head link[rel="preconnect"]', links => links.map(link => ({ + href: link.getAttribute('href'), + crossorigin: link.getAttribute('crossorigin'), + }))) + + // `imgAttrs` is applied after the prop, so it wins: 'use-credentials' and '' (anonymous) + expect(rendered).toEqual(['use-credentials', '']) + expect(hints).toHaveLength(2) + expect(hints).toContainEqual({ href: 'https://res.cloudinary.com', crossorigin: 'use-credentials' }) + expect(hints).toContainEqual({ href: 'https://res.cloudinary.com', crossorigin: 'anonymous' }) + + await page.close() + }) }) diff --git a/test/unit/bundle.test.ts b/test/unit/bundle.test.ts index 955804eee..eea4df32d 100644 --- a/test/unit/bundle.test.ts +++ b/test/unit/bundle.test.ts @@ -21,7 +21,7 @@ describe.skipIf(process.env.ECOSYSTEM_CI || isWindows)('nuxt image bundle size', image: { provider: 'ipx' }, }) - expect(roundToKilobytes(withImage.totalBytes - withoutImage.totalBytes)).toMatchInlineSnapshot(`"12.4k"`) + expect(roundToKilobytes(withImage.totalBytes - withoutImage.totalBytes)).toMatchInlineSnapshot(`"12.6k"`) }) })