【问题标题】:Preload image urls using new Image()使用 new Image() 预加载图片网址
【发布时间】:2022-08-19 00:30:48
【问题描述】:

我正在尝试在我的照片库中预加载或预取远程图像,但似乎new Image() 与 nextjs 的next/image 冲突。

这段代码在我迁移到 nextjs 之前(使用 CRA)运行良好。

 const img = new Image();
 img.src = photoToPreload.largeUrl;

任何建议都非常感谢。

    标签: next.js nextjs-image


    【解决方案1】:

    您可以将 next/image 的导入名称更改为另一个名称,例如

    import NextImage from 'next/image'
    

    这将帮助您为原始资料保留名称 Image

    但我认为你可以用next/image 以更好的方式实现同​​样的目标

    您只需将 priority 属性添加到您的 NextImage

    <NextImage {...otherProps} priority={true}/>
    

    它将生成preload link 以将您的图像预加载为重要资源。此外,您可以利用 next/image 包中的其他优化内容。

    【讨论】:

    • 我认为 OP 试图做的是预加载一系列图像而不是单个图像。
    • 没关系,尽管@Beaumont 使用这种方法是单个图像还是多个图像
    【解决方案2】:

    您可以尝试为 Next.js 的 Image 版本提供一个不冲突的别名(或使用您的自定义 Image 导入相反):

    // CommonJS style
    const { default: NextImage } = require("next/image");
    
    // ES module style
    import NextImage from "next/image";
    
    // alternatively
    import { default as NextImage } from "next/image";
    

    【讨论】:

      【解决方案3】:

      要预取 Carousel 的新图像,您可以使用下一张图像的 src 渲染一个不可见的 Image 组件,NextJS 会将其预加载给您,并在用户滑动到下一张幻灯片时准备好。如果您的轮播在首屏,请确保也将优先级添加到第一张幻灯片。

      import NextImage from 'next/image'
      () => {
        return (
          <div className="relative w-[300px]">
            <NextImage
              src={Screens[activeScreenIdx]}
              placeholder="blur"
              quality={100}
              layout="fill"
              objectFit="contain"
              sizes="350px"
            />
          {/* prefetch next image */}
            <NextImage
              {/* ..% Screen.length to avoid going out boundary */}
              src={Screens[(activeScreenIdx + 1) % Screens.length]}
              placeholder="blur"
              className="invisible" {/* just for preloading purposes */}
              quality={100}
              layout="fill"
              objectFit="contain"
              sizes="350px"
            />
          </div>
       )
      }
      

      【讨论】:

        猜你喜欢
        • 2013-10-17
        • 1970-01-01
        • 1970-01-01
        • 2021-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多