Skip to content

Commit 4280a79

Browse files
Merge pull request #123 from pradipchaudhary/project92
basic lazy loading images example
2 parents e05aa29 + 5010f3a commit 4280a79

File tree

7 files changed

+77
-0
lines changed

7 files changed

+77
-0
lines changed
2.37 MB
Loading
6.77 MB
Loading
2.87 MB
Loading

92-Lazy Loading Images/index.html

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>Lazy Loading Images</title>
7+
<link rel="stylesheet" href="styles.css" />
8+
</head>
9+
<body>
10+
<main>
11+
<h1>Lazy Loading Images Example</h1>
12+
13+
<div class="image-container">
14+
<img data-src="images/image1.jpg" alt="Image 1" />
15+
<img data-src="images/image2.jpg" alt="Image 2" />
16+
<img data-src="images/image3.jpg" alt="Image 3" />
17+
</div>
18+
</main>
19+
20+
<script src="script.js"></script>
21+
</body>
22+
</html>

92-Lazy Loading Images/readme.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Lazy Loading Images :art:
2+
3+
loading...

92-Lazy Loading Images/script.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
document.addEventListener("DOMContentLoaded", function () {
2+
const images = document.querySelectorAll("img[data-src]");
3+
4+
// Intersection Observer API to load images when they come into the viewport
5+
const observer = new IntersectionObserver(
6+
(entries, observer) => {
7+
entries.forEach((entry) => {
8+
if (entry.isIntersecting) {
9+
const img = entry.target;
10+
const src = img.getAttribute("data-src");
11+
12+
// Load the image
13+
img.setAttribute("src", src);
14+
img.removeAttribute("data-src");
15+
16+
// Stop observing once the image is loaded
17+
observer.unobserve(img);
18+
}
19+
});
20+
},
21+
{ rootMargin: "0px 0px 50px 0px" }
22+
);
23+
24+
// Start observing each image
25+
images.forEach((image) => {
26+
observer.observe(image);
27+
});
28+
});

92-Lazy Loading Images/styles.css

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
body {
2+
font-family: "Arial", sans-serif;
3+
margin: 0;
4+
padding: 0;
5+
}
6+
7+
main {
8+
margin: 20px;
9+
}
10+
11+
.image-container {
12+
display: flex;
13+
flex-wrap: wrap;
14+
gap: 10px;
15+
}
16+
17+
img {
18+
width: 100%;
19+
max-width: 300px;
20+
height: auto;
21+
border: 1px solid #ddd;
22+
border-radius: 8px;
23+
margin-bottom: 10px;
24+
}

0 commit comments

Comments
 (0)