我正在使用ReactJs开发一个网页游戏。它使用相当多的图像,当第一次尝试访问某个页面时,需要一些时间来加载所有图像。有没有办法预先预加载所有图像,以便应用程序启动后立即显示图像?
我已经尝试过一些图像预加载的方法(例如https://codesandbox.io/s/react-image-preload-ptosn?file=/src/App.js),但它们似乎不起作用还需要一些时间才能显示图像。
解决方案1: 告诉浏览器在页面加载时预加载游戏期间所需的所有图像。您可以通过为页面中的每个图像添加带有
<link>
的 rel="preload"
标签来实现此目的 <head>
:
<head>
<link rel="preload" href="path/to/image1.jpg" as="image">
<link rel="preload" href="path/to/image2.jpg" as="image">
</head>
这是一种非常简单的方法,但它不允许您在游戏加载时显示加载程序。
解决方案2: 使用 Javascript 的“Image”对象预加载图像。这样,您就可以检测这些图像的
onload
和 onerror
事件,并根据结果更新 UI。 这是您可以使用的示例挂钩:
function usePreloadImages(imageUrls) {
const [isLoading, setIsLoading] = useState(false);
let loadedCount = 0;
const totalCount = imageUrls.length;
useEffect(() => {
setIsLoading(true);
imageUrls.forEach((url) => {
const img = new Image();
img.onload = () => {
loadedCount += 1;
if (loadedCount === totalCount) {
setIsLoading(false);
}
};
img.src = URL;
});
})
}