I have two separate components, one that is intended for mobile devices and the other for desktop. Only one component should displayed at a time, depending on width of the user's browser window. Here's a condensed version that I have:
<script>
let innerWidth
</script>
<svelte:window bind:innerWidth />
<p>
Inner Width: {innerWidth}
</p>
{#if innerWidth > 800}
Desktop Content
{:else}
Mobile Content
{/if}
I noticed that when I load the page, {innerWidth} quickly switches from undefined to the appropriate value. For desktop users, this is a problem because the Mobile content is displayed because at the time of evaluating {#if innerWidth > 800}, Svelte has innerWidth = undefined.
Interestingly enough, this problem only occurs when I load the page directly. If I had this feature on /subpage, the intended functionality would work if I visited /index and then /subpage.
Is there a way to return the appropriate value on initial page load without it recognizing undefined? I would like to avoid using CSS media queries, but it is a last resort.
Is there a way to return the appropriate value on initial page load without it recognizing
undefined?
Not with the default configuration as SvelteKit uses server-side rendering on the first page load. There is no way to get that information on the server.
If you want to prevent displaying the wrong content you can also wrap your content in an additional #if.
{#if innerWidth != null}
{#if innerWidth > 800}
Desktop Content
{:else}
Mobile Content
{/if}
{/if}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With