kit icon indicating copy to clipboard operation
kit copied to clipboard

Unexpected DOM mutations during hydration

Open zhendalf opened this issue 3 years ago • 0 comments

Describe the bug

When hydrating a server-side-rendered page, Svelte applies numerous unexpected mutations—mainly removing and adding empty text nodes. The number of mutations seems to grow linearly with the number of components.

Here, for example, mutation logs from a bare-bone https://node.new/sveltekit project:

CleanShot 2023-01-17 at 15 35 17@2x

The expected behavior is to observe no mutations, unless something has changed. Please note that the issue I am describing is observed in production build, not only in development (where some mutations are justified).

Reproduction

To reproduce, one can just add a MutationObserver to app.html:

<body data-sveltekit-preload-data="hover">
  <div style="display: contents" id="kit-body">%sveltekit.body%</div>
</body>
<script>
  // Callback function to execute when mutations are observed
  const callback = (mutationList, observer) => {
    for (const mutation of mutationList) {
      console.log(mutation);
    }
  };

  // Create an observer instance linked to the callback function
  const observer = new MutationObserver(callback);

  // Start observing the target node for configured mutations
  observer.observe(document.getElementById('kit-body'), {
    attributes: true,
    childList: true,
    subtree: true,
    attributeOldValue: true
  });
</script>

Reproduction in github repo (contains SvelteKit skeleton, with mutation observer in app.html)

Logs

No response

System Info

System:
    OS: macOS 13.1
    CPU: (10) arm64 Apple M1 Pro
    Memory: 92.84 MB / 32.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.19.0 - ~/.nvm/versions/node/v16.19.0/bin/node
    npm: 8.19.3 - ~/.nvm/versions/node/v16.19.0/bin/npm
  Browsers:
    Chrome: 108.0.5359.124
    Firefox: 108.0.1
    Safari: 16.2
  npmPackages:
    @sveltejs/adapter-auto: ^1.0.0 => 1.0.1 
    @sveltejs/kit: ^1.0.0 => 1.1.1 
    svelte: ^3.54.0 => 3.55.1 
    vite: ^4.0.0 => 4.0.4

Severity

Performing DOM manipulations on load can have unpleasant side effects. I discovered the issue while trying to figure out, why CSS animation on a server-rendered element was being reset during hydration.

zhendalf avatar Jan 17 '23 08:01 zhendalf