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

如何在Svelte中仅加载随机选中的单张图片?

解决Svelte随机图片仅加载选中项的问题

你当前的写法会加载所有图片,是因为import语句会让构建工具(如Vite)将导入的资源视为必要依赖,提前打包并加载,不管你实际是否使用了该资源。要实现仅加载选中的图片,你可以直接使用图片路径字符串而非提前import,具体做法如下:

改进后的代码

<script>
    // 定义图片路径数组,直接使用字符串路径
    const heroImages = [
        '/lib/hero.webp',
        '/lib/heroTwo.webp'
    ];

    // 随机选择一个路径
    const randIndex = Math.floor(Math.random() * heroImages.length);
    const heroImg = heroImages[randIndex];
</script>

<img src={heroImg} alt="Some alt text">

注意事项

  • 如果你的图片放在SvelteKit的static目录下,路径需要改为/hero.webp这类直接根路径(比如图片在static/hero.webp,则路径写/hero.webp)。
  • 这种方式下,只有被选中的图片路径会被浏览器请求,避免了不必要的资源加载。

若需要保留$lib别名的写法,可以通过import.meta.env.BASE_URL拼接路径确保正确性:

<script>
    const baseUrl = import.meta.env.BASE_URL;
    const heroImages = [
        `${baseUrl}lib/hero.webp`,
        `${baseUrl}lib/heroTwo.webp`
    ];

    const randIndex = Math.floor(Math.random() * heroImages.length);
    const heroImg = heroImages[randIndex];
</script>

<img src={heroImg} alt="Some alt text">

内容的提问来源于stack exchange,提问作者Lee Morgan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 07:57:32