Vue Lazy Hydration: Ship the HTML Now, Hydrate the Component Later

2026-12-02来源 dev.toEnglish

Server-side rendering gets your HTML on screen fast. Then the browser downloads every component's JavaScript, runs it, and walks the DOM to attach listeners, all before the page is fully interactive. The footer newsletter form, the comments section three screens down, the "related products" carousel nobody scrolls to: they all hydrate on page load whether anyone touches them or not.

That's the cost lazy hydration targets. Since Vue 3.5, an async component can decide when it hydrates. The server still renders its full HTML, so users and crawlers see the content immediately, but the component's JavaScript isn't fetched or run until a condition you pick is met.

The four built-in strategies

Lazy hydration hangs off defineAsyncComponent, which you may already use for code splitting. You add a hydrate option and pass it one of the strategy functions. Each one is a separate import, so the ones you don't use get tree-shaken out.

import { defineAsyncComponent, hydrateOnIdle, hydrateOnVisible, hydrateOnInteraction, hydrateOnMediaQuery, } from "vue"; // Hydrate when the browser is idle (requestIdleCallback), max 2s wait const RelatedProducts = defineAsyncComponent({ loader: () => import("./RelatedProducts.vue"), hydrate: hydrateOnIdle(2000), }); // Hydrate when it scrolls into view (IntersectionObserver) const Comments = defineAsyncComponent({ loader: () => import("./Comments.vue"), hydrate: hydrateOnVisible({ rootMargin: "200px" }), }); // Hydrate on first interaction, then replay that event const ReviewForm = defineAsyncComponent({ loader: () => import("./ReviewForm.vue"), hydrate: hydrateOnInteraction(["focusin", "click"]), }); // Hydrate only when a media query matches const MobileNav = defineAsyncComponent({ loader: () => import("./MobileNav.vue"), hydrate: hydrateOnMediaQuery("(max-width: 768px)"), }); 

Then use them like any other component. Props and slots pass through the async wrapper untouched.

A few details are worth knowing. hydrateOnVisible accepts normal IntersectionObserver options, and a rootMargin is almost always worth setting: it starts the chunk download before the component reaches the viewport, so it's usually interactive by the time the user gets there. hydrateOnInteraction replays the event that triggered hydration once it finishes, so the first click on a lazy button isn't silently lost. And hydrateOnMediaQuery is a neat fit for components that only matter at one breakpoint, like a mobile menu that desktop visitors never need hydrated.

Writing your own strategy

The built-ins are intentionally low-level, and Vue exposes the same primitive they use. A strategy is a function that receives a hydrate callback and a forEachElement helper (a component's root can be a fragment, so there may be several elements), and returns an optional teardown.

Here's one that hydrates a chat widget only after the user has been on the page for a while, or immediately if they hover it:

import { defineAsyncComponent, type HydrationStrategy } from "vue"; const afterDelayOrHover = (ms: number): HydrationStrategy => (hydrate, forEachElement) => { let done = false; const run = () => { if (done) return; done = true; hydrate(); }; const timer = setTimeout(run, ms); const onEnter = () => run(); forEachElement((el) => el.addEventListener("mouseenter", onEnter, { once: true }), ); return () => { clearTimeout(timer); forEachElement((el) => el.removeEventListener("mouseenter", onEnter)); }; }; const ChatWidget = defineAsyncComponent({ loader: () => import("./ChatWidget.vue"), hydrate: afterDelayOrHover(8000), }); 

Two details matter here. The done flag makes sure hydrate runs once even if both triggers fire. And the teardown gives Vue a way to clean up, for example when the component unmounts before it ever hydrates, so a stray timer or listener doesn't fire against a component that's already gone.

If you're on Nuxt

Nuxt wraps the same mechanism in template syntax. Prefix a component with Lazy and add a hydrate-* attribute:

<template> <LazyComments hydrate-on-visible /> <LazyReviewForm hydrate-on-interaction="focusin" /> <LazyChatWidget :hydrate-after="8000" /> <LazyLegalFooter hydrate-never /> <LazyMobileNav hydrate-on-media-query="(max-width: 768px)" @hydrated="onNavReady" /> </template> 

Nuxt adds two strategies core doesn't ship as helpers: hydrate-never, for purely static content that should stay plain HTML, and hydrate-when, which hydrates when a boolean prop flips true. Every delayed component also emits @hydrated, handy for analytics or for focusing something once it's live. One rule: one strategy per component. There's also a defineLazyHydrationComponent macro if you'd rather configure it in script.

The tradeoffs

Lazy hydration isn't free performance; it moves work, and you should be deliberate about where.

Until a component hydrates, it's inert HTML. Links work because they're links, but @click handlers, v-model and anything stateful do nothing. That's fine for a comments list that only reads data. It's risky for a form someone might start typing into before hydrateOnVisible fires, which is why interaction-based hydration is the safer choice for inputs.

The trigger also starts a network request. If a user clicks a lazy component on a slow connection, they wait for the chunk to download before anything happens. Interaction replay keeps the click from vanishing, but it doesn't make it instant. Use rootMargin or idle hydration for anything people are likely to use soon.

And it only applies to SSR. In a client-only SPA, or when a component renders after a client-side navigation, there's nothing to hydrate, so the component just loads and mounts normally. That's the right behavior, but it means you won't see a difference in a dev setup without SSR.

The best candidates are big, below-the-fold, and rarely touched: comment threads, carousels, embeds, footers, chat widgets. Measure Total Blocking Time and INP before and after on a real page; if a component barely costs anything to hydrate, leaving it eager is simpler. The Vue async components guide and the Nuxt components docs cover every option.

原文:https://www.a8q9.cn/en/article/vue-lazy-hydration-ship-the-html-now-hydrate-the-component-later-a46d67.html

相关文章