sveltesapper

ReferenceError: document is not defined in Svelte 3


I'm trying in the <script> to manually document.createElement and then to appendChild an audio every time an eventListener is called to replace it. Everything works fine in the browser, apart a really quick error when the page loads but this lasts less then 100ms. There is an error in the Terminal as well

ReferenceError: document is not defined
    at Object (webpack:///./src/components/Record/Component.svelte?:26:17)

Seems that the above is called when document is not ready yet but afterwards it is fine, how to fix it? Or what is the preferred way to destroy and recreate components in Svelte world (Sapper)?


Solution

  • document is not defined on the server, so you need to guard against that in your component so that particular piece of code is only run in the browser.

    You can use the onMount function which is only run in the browser when the component has been rendered.

    <script>
      import { onMount } from 'svelte';
    
      onMount(() => {
        document.createElement(...);
        
        // ...
      });
    </script>