Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
17 changes: 17 additions & 0 deletions modules/homepage-head/assets.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { defineNitroPlugin } from 'nitropack/runtime'
import { buildAssetsURL } from '#internal/nuxt/paths'
import assets from '#skilld-head-assets'

export default defineNitroPlugin((nitro) => {
nitro.hooks.hook('render:html', (html, { event, streaming }) => {
const [path, query] = event.path.split('?', 2)
const pilot = path === '/' && new URLSearchParams(query).get('head') === 'lazy'
if (!streaming && pilot) {
html.head.push(`<meta name="skilld-head-assets" content="${assets.runtime} ${assets.options}">`)
}
else {
const href = buildAssetsURL(assets.eager).replaceAll('&', '&amp;').replaceAll('"', '&quot;')
html.head.push(`<link rel="modulepreload" crossorigin href="${href}">`)
}
})
})
82 changes: 82 additions & 0 deletions modules/homepage-head/module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { join } from 'node:path'
import { addTypeTemplate, createResolver, defineNuxtModule } from '@nuxt/kit'

const stockPlugin = /[/\\]head[/\\]runtime[/\\]plugins[/\\]unhead(?:-stream)?\.client\.js$/
const assetName = /^(?:[\w.-]+\/)*[\w.-]+\.m?js$/
const assetsId = '#skilld-head-assets'

export default defineNuxtModule({
meta: { name: 'skilld-homepage-head' },
setup(_, nuxt) {
if (nuxt.options.dev || process.env.NODE_ENV === 'test')
return

const { resolve } = createResolver(import.meta.url)
const client = resolve('./runtime/head.client')
const assets = { eager: '', runtime: '', options: '' }
let eagerSource = ''

nuxt.hook('app:resolve', (app) => {
const head = app.plugins.find(plugin => stockPlugin.test(plugin.src))
const scripts = app.plugins.find(plugin => plugin.src.endsWith('/modules/@nuxt-scripts/plugin.mjs'))
if (!head || !scripts)
throw new Error('Homepage head requires Nuxt head and the Cloudflare Analytics registry plugin.')

// Cloudflare Analytics is the only registry entry. SSR emits its beacon once.
scripts.mode = 'server'
eagerSource = head.src.replaceAll('\\', '/')
nuxt.options.alias['#skilld-eager-head'] = head.src
nuxt.options.alias['#skilld-install-head'] = join(head.src, '../../install-client-head.js')
head.src = client
})

nuxt.hook('build:manifest', (manifest) => {
if (!eagerSource)
throw new Error('Homepage head could not find the stock Nuxt client plugin.')

for (const [key, chunk] of Object.entries(manifest)) {
if (!assetName.test(chunk.file))
continue
// Rolldown can share the plugin options between the eager and lazy entries.
if ([key, chunk.src, chunk.name].some(source => source?.includes('unhead-options'))) {
assets.options = chunk.file
continue
}
if (!chunk.isDynamicEntry)
continue

const sources = [key, chunk.src ?? ''].map(source => source.replaceAll('\\', '/').split('?')[0]!)
if (sources.some(source => eagerSource.endsWith(`/${source.replace(/^(?:\.\.\/)+/, '')}`) || source === eagerSource)) {
assets.eager = chunk.file
}
else if (sources.some(source => source.endsWith('/node_modules/unhead/dist/chunks/runtime.mjs'))) {
assets.runtime = chunk.file
}
else {
continue
}

chunk.preload = false
chunk.prefetch = false
}

if (Object.values(assets).some(file => !file))
throw new Error(`Homepage head is missing an emitted chunk: ${JSON.stringify(assets)}`)
})

addTypeTemplate({
filename: 'types/skilld-head-assets.d.ts',
getContents: () => `declare module '${assetsId}' {
const assets: { eager: string, runtime: string, options: string }
export default assets
}`,
}, { nuxt: false, nitro: true })

nuxt.hook('nitro:config', (config) => {
config.virtual ||= {}
config.virtual[assetsId] = () => `export default ${JSON.stringify(assets)}`
config.plugins ||= []
config.plugins.push(resolve('./assets.server'))
})
},
})
139 changes: 139 additions & 0 deletions modules/homepage-head/runtime/head.client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { headSymbol } from '@unhead/vue'
import { HookableCore } from 'hookable'
import { createHead } from 'unhead/lazy'
import { defineNuxtPlugin } from '#app/nuxt'
import { buildAssetsURL } from '#build/paths.mjs'
import { installClientHead } from '#skilld-install-head'

declare global {
interface Window {
/** Set before navigation to compare against Nuxt's eager renderer with the same SSR response. */
__SKILLD_EAGER_HEAD__?: boolean
}
}

export default defineNuxtPlugin({
name: 'nuxt:head',
enforce: 'pre',
async setup(nuxtApp): Promise<void> {
const assets = document.head.querySelector<HTMLMetaElement>('meta[name="skilld-head-assets"]')
if (!assets || !nuxtApp.payload.serverRendered || window.__SKILLD_EAGER_HEAD__) {
assets?.remove()
const { default: plugin } = await import('#skilld-eager-head')
await plugin(nuxtApp)
return
}

const hooks = new HookableCore()
const importPlugins = () => import('#build/unhead-options.mjs').then(options => options.default.plugins)
let loadingPlugins: ReturnType<typeof importPlugins> | undefined
const options = {
disableDefaults: true,
hookable: hooks,
lazyPlugins: () => loadingPlugins ?? importPlugins(),
}
const head = createHead(options)
let hydrated = false
let loading: Promise<unknown> | undefined

function load() {
if (loading)
return loading

performance.mark('skilld-head-load-start')
loadingPlugins = importPlugins()
loading = Promise.all([head.load(), loadingPlugins]).then(() => {
performance.mark('skilld-head-load-end')
}).catch((error: unknown) => {
loading = undefined
loadingPlugins = undefined
console.error('Homepage head could not load', error)
})
return loading
}

const push = head.push
head.push = (input, options) => {
const entry = push(input, options)
const { patch, dispose } = entry
if (hydrated || options?.onRendered)
void load()
entry.patch = (input) => {
patch(input)
if (hydrated)
void load()
}
entry.dispose = () => {
dispose()
if (hydrated)
void load()
}
return entry
}

const use = head.use
head.use = (plugin) => {
use(plugin)
if (hydrated)
void load()
}
hooks.hook('script:updated', ({ script }) => {
if (script.status === 'loading')
void load()
})

const installableHead = Object.assign(head, {
install(app: typeof nuxtApp.vueApp) {
app.config.globalProperties.$unhead = app.config.globalProperties.$head = head
app.provide(headSymbol, head)
},
})
// Nuxt installs only push, hooks, render and install before the shell activates.
installClientHead(nuxtApp, installableHead as unknown as Parameters<typeof installClientHead>[1])

const connection = (navigator as Navigator & { connection?: { rtt?: number } }).connection
const rtt = connection?.rtt
if (!rtt || rtt >= 150) {
const warm = () => {
if (loading)
return
performance.mark('skilld-head-warm')
for (const file of assets.content.split(' ')) {
const link = document.createElement('link')
link.rel = 'modulepreload'
link.setAttribute('fetchpriority', 'low')
link.crossOrigin = ''
link.href = buildAssetsURL(file)
document.head.appendChild(link)
}
}
// Hydration can last until the first click on a slow connection.
if ('requestIdleCallback' in globalThis)
requestIdleCallback(warm, { timeout: 500 })
else
setTimeout(warm)
}
assets.remove()

nuxtApp.hook('app:suspense:resolve', () => {
if (hydrated)
return
head.finishHydration()
hydrated = true
performance.mark('skilld-head-hydrated')
})
nuxtApp.hook('app:created', () => {
nuxtApp.$router.beforeEach((to, from) => {
if (from.matched.length && to.path !== from.path)
void load()
})
})
nuxtApp.hook('page:start', () => {
if (hydrated)
void load()
})
nuxtApp.hook('app:error', () => {
void load()
})
},
})
1 change: 1 addition & 0 deletions nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export default defineNuxtConfig({
'@nuxt/ui',
'@nuxt/fonts',
'@nuxt/scripts',
'./modules/homepage-head/module.ts',
'@nuxtjs/seo',
'@nuxtjs/mcp-toolkit',
'@nuxt/a11y',
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,17 +114,20 @@
"@nuxtjs/mcp-toolkit": "catalog:",
"@playwright/test": "catalog:",
"@types/node": "catalog:",
"@unhead/vue": "catalog:",
"@vue/test-utils": "catalog:",
"axe-core": "catalog:",
"better-sqlite3": "catalog:",
"eslint": "catalog:",
"eslint-plugin-harlanzw": "catalog:",
"happy-dom": "catalog:",
"hookable": "catalog:",
"lint-staged": "catalog:",
"nuxtseo-devtools-host": "catalog:",
"site-typecheck": "workspace:*",
"tsx": "catalog:",
"typescript": "catalog:",
"unhead": "catalog:",
"vitest": "catalog:",
"vue-tsc": "catalog:",
"wrangler": "catalog:"
Expand Down
13 changes: 13 additions & 0 deletions patches/@nuxt__scripts@1.3.10.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
diff --git a/dist/runtime/registry/cloudflare-web-analytics.js b/dist/runtime/registry/cloudflare-web-analytics.js
index 8deda48f1a57cc86890d8569d4f785e74a3c8458..2452bf75f13d33c7374d704155cc9c1c92c0b0e5 100644
--- a/dist/runtime/registry/cloudflare-web-analytics.js
+++ b/dist/runtime/registry/cloudflare-web-analytics.js
@@ -11,7 +11,7 @@ export function useScriptCloudflareWebAnalytics(_options) {
schema: import.meta.dev ? CloudflareWebAnalyticsOptions : void 0,
scriptOptions: {
// we want to load earlier so that the web vitals reports are correct
- trigger: "client",
+ trigger: options.scriptOptions?.trigger ?? "client",
use() {
return { __cfBeacon: window.__cfBeacon };
}
Loading
Loading