@@ -59,7 +59,6 @@ export default function LazyImage({
59
59
useEffect ( ( ) => {
60
60
const adjustedImageSrc =
61
61
adjustImgSize ( src , maxWidth ) || defaultPlaceholderSrc
62
-
63
62
// 加载原图
64
63
const img = new Image ( )
65
64
img . src = adjustedImageSrc
@@ -68,7 +67,6 @@ export default function LazyImage({
68
67
handleImageLoaded ( adjustedImageSrc )
69
68
}
70
69
img . onerror = handleImageError
71
-
72
70
const observer = new IntersectionObserver (
73
71
entries => {
74
72
entries . forEach ( entry => {
@@ -81,11 +79,9 @@ export default function LazyImage({
81
79
} ,
82
80
{ rootMargin : '50px 0px' } // Adjust the rootMargin as needed to trigger the loading earlier or later
83
81
)
84
-
85
82
if ( imageRef . current ) {
86
83
observer . observe ( imageRef . current )
87
84
}
88
-
89
85
return ( ) => {
90
86
if ( imageRef . current ) {
91
87
observer . unobserve ( imageRef . current )
@@ -97,6 +93,7 @@ export default function LazyImage({
97
93
const imgProps = {
98
94
ref : imageRef ,
99
95
src : currentSrc ,
96
+ 'data-src' : src ,
100
97
alt : alt ,
101
98
onLoad : handleThumbnailLoaded , // 缩略图加载完成
102
99
onError : handleImageError // 添加onError处理函数
@@ -118,14 +115,19 @@ export default function LazyImage({
118
115
imgProps . height = height
119
116
}
120
117
if ( className ) {
121
- imgProps . className = className
118
+ imgProps . className = className + ' lazy-image-placeholder'
122
119
}
123
120
if ( style ) {
124
121
imgProps . style = style
125
122
}
126
123
if ( onClick ) {
127
124
imgProps . onClick = onClick
128
125
}
126
+
127
+ if ( ! src ) {
128
+ return null
129
+ }
130
+
129
131
return (
130
132
< >
131
133
{ /* eslint-disable-next-line @next/next/no-img-element */ }
@@ -136,6 +138,21 @@ export default function LazyImage({
136
138
< link rel = 'preload' as = 'image' href = { adjustImgSize ( src , maxWidth ) } />
137
139
</ Head >
138
140
) }
141
+ < style >
142
+ { `
143
+ .lazy-image-placeholder{
144
+
145
+ background:
146
+ linear-gradient(90deg,#0001 33%,#0005 50%,#0001 66%)
147
+ #f2f2f2;
148
+ background-size:300% 100%;
149
+ animation: l1 1s infinite linear;
150
+ }
151
+ @keyframes l1 {
152
+ 0% {background-position: right}
153
+ }
154
+ ` }
155
+ </ style >
139
156
</ >
140
157
)
141
158
}
0 commit comments