Fixing My “Flickering” Issue With SvelteKit Server-Side Rendering
Since using SvelteKit, I have noticed an peculiar issue when loading data to a page. It is somewhat difficult for me to describe so I will link an example.
When you load this page, you should see a number between 0 and 99 which is quickly replaced by another such number. It might be really quick. Refreshing while disabling your browser cache might make it more pronounced. I’ve long wondered why such behavior existed, but I recently asked on the r/sveltejs subreddit and received two relevant suggestions.
The first was to load the data from
+page.server.js instead of
+page.js is run on both the server and the client while
+page.server.js is only run on the server. Meaning the
value that I was seeing at first was from the server and then the
second value was from re-running
+page.js on the client.
an example of this technique.
However, on another project that already used
+page.server.js to load its data was still experiencing
this issue. Another commenter explained that this was the result of
server-side rendering. Which makes sense. I don’t REALLY
understand server-side rendering, but my basic understanding is that
the server starts and then hands the website off to the client to
handle the rest. For this other project I went to the
+page.js of the relevant route and added
export const ssr = false; . This resolved the flickering
I have a feeling that this solution is bad practice and a hack.
A commenter suggested that I don’t need to set SSR to false and
instead can just use
+page.server.js “and the SSR
will take care of itself”.
console.log I have noticed differences between
these 3 approaches. In the original approach it logs both the log from
+page.js and the
+page.svelte on the
server and in the browser (client). Only the numbers that are longed
output on the server is the same but on the client it only logs from
when I disable SSR
+page.js I get no logs on the server and get both
lines on the client. I think this illustrates how SSR works. Without
SSR, the client is responsible to run all scripts.
Anyways, server-side rendering is something I should understand more if I want to master web development.
Link to code