diff --git a/components/LazyImage.js b/components/LazyImage.js
index 3e44eb4c..b87f62cc 100644
--- a/components/LazyImage.js
+++ b/components/LazyImage.js
@@ -1,7 +1,6 @@
import { siteConfig } from '@/lib/config'
import Head from 'next/head'
-import React, { useEffect, useRef, useState } from 'react'
-
+import { useEffect, useRef, useState } from 'react'
/**
* 图片懒加载
* @param {*} param0
@@ -20,26 +19,35 @@ export default function LazyImage({
onLoad,
style
}) {
+ const maxWidth = siteConfig('IMAGE_COMPRESS_WIDTH')
const imageRef = useRef(null)
- const [imageLoaded, setImageLoaded] = useState(false)
+ const [adjustedSrc, setAdjustedSrc] = useState(
+ placeholderSrc || siteConfig('IMG_LAZY_LOAD_PLACEHOLDER')
+ )
+
if (!placeholderSrc) {
placeholderSrc = siteConfig('IMG_LAZY_LOAD_PLACEHOLDER')
}
+ /**
+ * 图片加载成功回调
+ */
const handleImageLoad = () => {
- setImageLoaded(true)
if (typeof onLoad === 'function') {
onLoad() // 触发传递的onLoad回调函数
}
}
useEffect(() => {
+ const adjustedImageSrc = adjustImgSize(src, maxWidth)
+ setAdjustedSrc(adjustedImageSrc)
+
const observer = new IntersectionObserver(
- (entries) => {
- entries.forEach((entry) => {
+ entries => {
+ entries.forEach(entry => {
if (entry.isIntersecting) {
const lazyImage = entry.target
- lazyImage.src = src
+ lazyImage.src = adjustedImageSrc
observer.unobserve(lazyImage)
}
})
@@ -56,12 +64,12 @@ export default function LazyImage({
observer.unobserve(imageRef.current)
}
}
- }, [src])
+ }, [src, maxWidth])
// 动态添加width、height和className属性,仅在它们为有效值时添加
const imgProps = {
ref: imageRef,
- src: imageLoaded ? src : placeholderSrc,
+ src: priority ? adjustedSrc : placeholderSrc,
alt: alt,
onLoad: handleImageLoad
}
@@ -87,12 +95,39 @@ export default function LazyImage({
if (style) {
imgProps.style = style
}
- return (<>
- {/* eslint-disable-next-line @next/next/no-img-element */}
-
- {/* 预加载 */}
- {priority &&