You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SvelteKit初始页面加载时window.innerWidth返回undefined的解决方法

解决Svelte初始加载时innerWidth为undefined的问题

方案1:初始化时直接赋值window.innerWidth

在脚本里给innerWidth设置初始值,同时兼容服务器端渲染(SSR)场景:

<script>
    // 非SSR环境直接取window.innerWidth,SSR时设为合理默认值(比如800,对应桌面端初始判断)
    let innerWidth = typeof window !== 'undefined' ? window.innerWidth : 800;
</script>

<svelte:window bind:innerWidth />

<p>
  Inner Width: {innerWidth}
</p>

{#if innerWidth > 800}
    Desktop Content
{:else}
    Mobile Content
{/if}

页面初始化时innerWidth就有了正确的初始值,不会出现undefined导致的移动端内容闪现。后续Svelte的bind:innerWidth会自动同步窗口尺寸变化。

方案2:使用onMount钩子初始化

如果你的项目是纯客户端渲染(无需考虑SSR),可以用onMount确保在客户端环境下赋值:

<script>
    import { onMount } from 'svelte';
    let innerWidth;

    onMount(() => {
        // onMount仅在客户端执行,此时window对象一定存在
        innerWidth = window.innerWidth;
    });
</script>

<svelte:window bind:innerWidth />

<p>
  Inner Width: {innerWidth}
</p>

{#if innerWidth > 800}
    Desktop Content
{:else if innerWidth !== undefined}
    Mobile Content
{/if}

这里给else分支加了innerWidth !== undefined的判断,避免组件挂载前显示错误内容,也可以根据需求替换成加载状态提示。

问题原因说明

直接加载页面时,组件初始化阶段Svelte还未完成与window对象的绑定,所以innerWidth初始为undefined;而从/index跳转至/subpage属于客户端路由跳转,此时浏览器已存在window对象,Svelte能立刻获取到正确的窗口宽度值,因此不会出现问题。

内容的提问来源于stack exchange,提问作者R Barnes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:54:35