The Problem
SvelteKit runs the code in the script
tag both on the server and in the client, based on the circumstances. Meaning that you’ll most likely get an error that document
or window
is not defined.
<script>document.getElementByClass("test")</script>
This code will fail as document
not accessible on the server.
The Solution
SvelteKit allows us to run client side only code in two ways. You can choose to either use the onMount
function, or the browser
flag.
<script>
import { onMount } from 'svelte';
import { browser } from '$app/environment';
onMount(() => {
document.getElementByClass("test")
})
// or...
if (browser) {
document.getElementByClass("test")
}
</script>
The browser
flag is also good to use when the script context is module
. Source here.
<script context="module">
import { browser } from '$app/environment';
export async function load({ fetch }) {
if (!browser) {
// code here runs only on the server
}
return {
// something to return
}
}
<script>
Importing a library
Sometimes, you might have a problem importing a library becuase some of its dependenices expect the DOM to be avaible. In that case, you can import it like so;
<script>
import { onMount } from 'svelte';
onMount(async () => {
const module = await import('some-lib');
const SomeLib = module.default;
// use module here...
});
</script>
This snippet was from this Stack Overflow question.