Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte transitions and animations on page load

I am currently working on a website using Svelte and Sapper. I'm using Svelte transitions to animate some of the page elements. Whenever I change to a new page route, the transitions animate correctly. But when I load the page for the first time, they do not animate.

How does Svelte handle animations on page load? Do I need to use onMount() to get them to work properly?

like image 267
Nathanael Troyer Avatar asked Oct 16 '20 21:10

Nathanael Troyer


2 Answers

Because Sapper server-renders pages, intro: true would result in an awkward flash of visible content becoming invisible then transitioning back in.

To avoid that, you need to prevent content being server-rendered in the first place. The easiest way to do that is indeed to use onMount:

<script>
  import { onMount } from 'svelte';

  let ready = false;
  onMount(() => ready = true);
</script>

<div class="always-visible">
  {#if ready}
    <div class="visible-on-mount">...</div>
  {/if}
</div>
like image 95
Rich Harris Avatar answered Nov 04 '22 21:11

Rich Harris


From the Svelte docs:

By default intro transitions will not play on first render. You can modify this behaviour by setting intro: true when you create a component.

So if you want your entire app to have transitions on load by default throughout the whole app you just do the following in main.js:

import App from './App.svelte';

const app = new App({
    target: document.body,
    intro: true
});

EDIT:

See Rich's answer for Sapper usage.

like image 26
JHeth Avatar answered Nov 04 '22 21:11

JHeth