Skip to content
Open
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
4 changes: 4 additions & 0 deletions src/runtime/components/SwitchLocalePathLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { hasProtocol } from 'ufo'
import { nuxtLinkDefaults } from '#build/nuxt.config.mjs'
import { useComposableContext } from '../composable-context'
import { useNuxtI18nContext } from '../context'
import { markSwitchLocalePathLink } from '../shared/switch-locale-path'

import type { PropType } from 'vue'

Expand Down Expand Up @@ -68,6 +69,9 @@ export default defineComponent({
},
inheritAttrs: false,
setup(props, { slots, attrs }) {
if (import.meta.server) {
markSwitchLocalePathLink(useNuxtApp().ssrContext)
}
return () => [
h(Comment, `${__SWITCH_LOCALE_PATH_LINK_IDENTIFIER__}-[${props.locale}]`),
h(SlpComponent, { ...attrs, ...props }, slots.default),
Expand Down
4 changes: 3 additions & 1 deletion src/runtime/plugins/switch-locale-path-ssr.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { defineNuxtPlugin, useNuxtApp } from '#imports'
import { useSwitchLocalePath } from '#i18n'
import { escapeHtmlAttr } from '../shared/utils'
import { hasSwitchLocalePathLink } from '../shared/switch-locale-path'

const identifier = __SWITCH_LOCALE_PATH_LINK_IDENTIFIER__
const switchLocalePathLinkWrapperExpr = new RegExp(
Expand All @@ -17,7 +18,8 @@ export default defineNuxtPlugin({
const nuxt = useNuxtApp(_nuxt._id)
const switchLocalePath = useSwitchLocalePath(nuxt)
nuxt.hook('app:rendered', (ctx) => {
if (ctx.renderResult?.html == null) { return }
// scanning the whole html costs time on every large page, so skip renders without a link
if (ctx.renderResult?.html == null || !hasSwitchLocalePathLink(ctx.ssrContext)) { return }

ctx.renderResult.html = ctx.renderResult.html.replaceAll(
switchLocalePathLinkWrapperExpr,
Expand Down
12 changes: 12 additions & 0 deletions src/runtime/shared/switch-locale-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { NuxtSSRContext } from '#app'

// server renders that contain a `SwitchLocalePathLink`, so only those pay for the html rewrite
const renders = new WeakSet<NuxtSSRContext>()

export function markSwitchLocalePathLink(ssrContext: NuxtSSRContext | undefined) {
if (ssrContext) { renders.add(ssrContext) }
}

export function hasSwitchLocalePathLink(ssrContext: NuxtSSRContext | undefined) {
return !!ssrContext && renders.has(ssrContext)
}
Loading