imagesveltesveltekit

Why "error Image is not defined" in svelte local, but working in REPL?


I'm getting this error:

ReferenceError: Image is not defined

The code is in a component and looks like this:

    // Preload images
    for (const name in images) {
      (new Image()).src = images[name]
    }

The only thing I did is a exact copy of this working REPL in local, there it works but in local it doesn't. These lines are under the piece.svelte component.

I'm very new at js, I imagine I'm missing some basics. Any Idea?


Solution

  • Image is part of the browser API, it creates an <img> element and cannot be used at the top level when using SvelteKit: During server-side rendering it will not be available.

    You can access the DOM in onMount.