简体   繁体   English

在页面加载之前预加载 nextjs 图像

[英]Preload nextjs Images before page load

Ignoring the fact that this is generally considered a bad practice, I'm trying to understand how I can preload a set of images either before a page transition or prior to rendering my page.忽略这通常被认为是一种不好的做法这一事实,我试图了解如何在页面转换之前或在呈现我的页面之前预加载一组图像。 My use case requires quite a few large image files to be displayed at the same time and animated onto the screen.我的用例需要同时显示相当多的大图像文件并在屏幕上设置动画。 I'd like to essentially have a loading spinner on the page while the initial set of large images is downloaded and cached in the browser and then I can show them all at once.我想在页面上有一个加载微调器,同时将初始的大图像集下载并缓存在浏览器中,然后我可以一次显示它们。

If I want to do this with standard react, I can do something like this:如果我想用标准反应做到这一点,我可以这样做:

    await Promise.all(
        images.map(async (url) => {
            return new Promise((resolve) => {
                const image = new Image();
                image.src = url;
                image.onload = () => resolve(true);
            });    
        })
    )}

And then have an isLoading boolean get flipped when everything is done loading.然后让isLoading boolean 在所有内容加载完成后翻转。 With the nextjs Image components, though, I can't load those initial images until they are actually added to the dom.但是,使用 nextjs Image组件,在将它们实际添加到 dom 之前,我无法加载这些初始图像。 The URL for those images changes based on various conditions so I can't really use the original solution to preload them.这些图像的 URL 会根据各种条件而变化,因此我不能真正使用原始解决方案来预加载它们。

Is there a way to force the browser to download the image sources generated from my nextjs <Image> components before they get added to the dom?有没有办法强制浏览器在将我的 nextjs <Image>组件生成的图像源添加到 dom 之前下载它们?

Have you tried adding priority=true to the Image component?您是否尝试将 priority=true 添加到 Image 组件?

Read details here: next-image docs在此处阅读详细信息: 下一个图像文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM