Nextjs 图像:使用链接预加载进行预加载,但在窗口加载事件后几秒钟内未使用

问题描述 投票:0回答:5

我正在使用 Nextjs ,一个基于 React 的框架,我正在尝试在 Next.js 提供的

Image
组件中显示 logo.png 图像。

我有这个文件夹:

public/img

这是我的代码:

<Image
  src={'/img/logo.png'}
  width='154'
  height='82'
  alt='logo'
  layout='responsive'
  priority={true}
/>

我在控制台中收到此错误:

资源 http://localhost:3001/_next/image?url=%2Fimg%2Flogo.png&w=640&q=75 是 使用链接预加载进行预加载,但在几秒钟内未使用 窗口的加载事件。请确保它有合适的

as
值并且是有意预加载的。

有什么帮助吗?

javascript reactjs google-chrome next.js next-images
5个回答
12
投票

向下一个图像添加“placeholder”和“blurDataURL”道具并删除“priority”道具,有助于解决此问题

<Image
  src={'/img/logo.png'}
  width='154'
  height='82'
  alt='logo'
  placeholder="blur"
  blurDataURL={'/img/logo.png'}
/>

我删除了布局标签,因为我使用的是 Next.js 版本 13.1.1

如果上述方法不起作用,请确保您传递了 Sizes 属性

尺寸=“(最大宽度:768px)100vw,(最大宽度:1200px)50vw,33vw”

从文档中阅读更多内容

提供有关图像在不同断点处的宽度的信息的字符串。尺寸的值将极大地影响使用填充或样式为具有响应尺寸的图像的性能

例如,如果您知道您的样式会导致图像在移动设备上为全宽、在平板电脑上为 2 列布局、在桌面显示器上为 3 列布局,则应包含尺寸属性,例如以下:

import Image from 'next/image'
const Example = () => (
  <div className="grid-element">
    <Image
      src="/example.png"
      fill
      sizes="(max-width: 768px) 100vw,
              (max-width: 1200px) 50vw,
              33vw"
    />
  </div>
)

此示例的大小可能会对性能指标产生巨大影响。如果没有 33vw 大小,从服务器选择的图像宽度将是所需宽度的 3 倍。由于文件大小与宽度的平方成正比,如果没有大小,用户将下载比所需大小大 9 倍的图像。


4
投票

为我解决这个问题的事情实际上在 Next.js Image Github 中有所暗示。

如果您尝试将实际源路径作为 src 的值,它将不起作用。

为了使用 src,您需要导入它:

import frank from '/public/frank-banner.png';

这样当你真正在Image组件中使用它时:

<Image src={frank} width={xx} height={xx}/>

3
投票

如果您使用链接,只需添加 as='image' 像这样

<Link href="/" as={'image'}>
              <Image
                priority={true}
                src="/images/profile.jpg"
                className={utilStyles.borderCircle}
                height={108}
                width={108}
                alt=""
              />
            </Link>

只需添加

as='image'
,就可以解决我的问题


0
投票

只需将优先级设置为“true”,相当于 rel="preload"。

Html 中预加载的图像

<link rel="preload" as="image" href="image.jpg">

下一个:

<Image
    src="/images/image.jpg"

    width="800"
    height="600"
    priority={true}
 />

问题出在 chrome 的预加载上,因为它会加载未使用的图像。但加载是正确的。 自从这个小修正后,我就不再有错误消息了

以下是一些来源: https://github.com/GoogleChromeLabs/preload-webpack-plugin/issues/8 https://abstack.pk/post/learn-how-to-preload-images-in-nextjs

享受


0
投票

在 ThemeContextProvider (./src/context/Themecontext.jsx:20:78) 摘要:“2350462168” 7 | const getFormLocalStorage = () => { 8 | if(窗口类型!==未定义){

9 | const value = localStorage.getItem("主题"); | ^ 10 | 10返回值|| “光”; 11 | 11 }

© www.soinside.com 2019 - 2024. All rights reserved.