AtomicElmo
AtomicElmo

Reputation: 23

How can I execute js when loading a sub route on a static build in Sveltekit

I never noticed this before, but I've encountered a weird issue in my Sveltekit application. To put it simply, I have a ("/map") sub route that when refreshed/loaded directly as the sub route won't execute any JS, I noticed this is the general case for all sub routes. when loading a sub route, no matter which one ("/about"), ("/map") it renders all the HTML and CSS perfectly but won't execute any JS, UNLESS you load the root first ("/") and navigate via links or goTo to a sub route ("/map").

I'm using a static adapter, but this also happens with the adapter-auto. There is no issue in the dev environment, when running

npm run dev

but when testing the production build

npm run build

and running

npm run preview

the issue arises.

I want people to be able to load ("https://www.example.com/map") directly instead of having to go to ("https://www.example.com/") first and route from there just so that Sveltekit can execute the JS hence load the imports and other necesseties for the map to properly function and laod.

Upvotes: 1

Views: 50

Answers (2)

AtomicElmo
AtomicElmo

Reputation: 23

I solved this removing "export const csr = dev;" in my +page.js/ts file because it somehow has an effect on my production build.

Upvotes: 0

José Ramírez
José Ramírez

Reputation: 2325

What you are experiencing is SSR: Server-Side Rendering. It is not that it doesn't run, it runs in the server side, not the browser side.

SSR in Sveltekit runs the code in the <script> tags in the NodeJS server, and then simply transmit the resulting HTML. Then, during hydration, the Svelte runtime executes effects, transitions, etc.

Upvotes: 0

Related Questions