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.
2
Answers
I solved this by creating a new layout in my "routes" folder, so basically this is how my routes folder looks like:
This way any sub folder created as a new layout like (main) will be treated as a root folder and execute even JS on a refresh or load.
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.