feat: 图片lazy loading

This commit is contained in:
2026-08-12 18:15:41 +08:00
parent 67070e5fc4
commit 60131d6fa9
5 changed files with 135 additions and 9 deletions

View File

@@ -0,0 +1,131 @@
---
interface Props {
src: string;
alt?: string;
width?: number;
height?: number;
class?: string;
}
const {
src,
alt = "",
width,
height,
class: className = ""
} = Astro.props;
---
<div
class={`lazy-image ${className}`}
data-src={src}
style={`aspect-ratio:${width}/${height}`}
>
<div class="placeholder"></div>
<img
class="real-image"
alt={alt}
width={width}
height={height}
loading="lazy"
decoding="async"
/>
</div>
<style>
.lazy-image {
position: relative;
overflow: hidden;
width: 100%;
height: 100%;
}
.lazy-image img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.placeholder {
position: absolute;
inset: 0;
background: #f3f4f6;
background-image: linear-gradient(
90deg,
#f3f4f6 0%,
#e5e7eb 50%,
#f3f4f6 100%
);
background-size: 200% 100%;
animation: loading 1.5s infinite;
}
@keyframes loading {
from {
background-position: 200% 0;
}
to {
background-position: -200% 0;
}
}
.real-image {
opacity: 0;
transition: opacity .35s ease;
}
.real-image.loaded {
opacity: 1;
}
</style>
<script>
function initLazyImages() {
const images = document.querySelectorAll(".lazy-image");
const observer = new IntersectionObserver(
entries => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
const container = entry.target as HTMLElement;
const img = container.querySelector(
".real-image"
) as HTMLImageElement;
const src = container.dataset.src;
if (!src) return;
img.src = src;
img.onload = () => {
img.classList.add("loaded");
const placeholder =
container.querySelector(".placeholder");
placeholder?.remove();
};
observer.unobserve(container);
});
},
{
rootMargin: "300px"
}
);
images.forEach(img => observer.observe(img));
}
initLazyImages();
</script>