Skip to content

Commit 3675999

Browse files
authored
Merge pull request #196 from sveltejs/gh-172
document hydration
2 parents b789781 + 59b65eb commit 3675999

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

content/guide/13-advanced.md

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,46 @@ It's easier to show the effect of this than to describe it. Open the following e
6868
transitions: { slide }
6969
};
7070
</script>
71-
```
71+
```
72+
73+
74+
### Hydration
75+
76+
If you're using [server-side rendering](#server-side-rendering), it's likely that you'll need to create a client-side version of your app *on top of* the server-rendered version. A naive way to do that would involve removing all the existing DOM and rendering the client-side app in its place:
77+
78+
```js
79+
import App from './App.html';
80+
81+
const target = document.querySelector('#element-with-server-rendered-html');
82+
83+
// avoid doing this!
84+
target.innerHTML = '';
85+
new App({
86+
target
87+
});
88+
```
89+
90+
Ideally, we want to reuse the existing DOM instead. This process is called *hydration*. First, we need to tell the compiler to include the code necessary for hydration to work by passing the `hydratable: true` option:
91+
92+
```js
93+
const { code } = svelte.compile(source, {
94+
hydratable: true
95+
});
96+
```
97+
98+
(Most likely, you'll be passing this option to [rollup-plugin-svelte](https://github.com/rollup/rollup-plugin-svelte) or [svelte-loader](https://github.com/sveltejs/svelte-loader).)
99+
100+
Then, when we instantiate the client-side component, we tell it to use the existing DOM with `hydrate: true`:
101+
102+
```js
103+
import App from './App.html';
104+
105+
const target = document.querySelector('#element-with-server-rendered-html');
106+
107+
new App({
108+
target,
109+
hydrate: true
110+
});
111+
```
112+
113+
> It doesn't matter if the client-side app doesn't perfectly match the server-rendered HTML — Svelte will repair the DOM as it goes.

0 commit comments

Comments
 (0)