File tree Expand file tree Collapse file tree 7 files changed +77
-0
lines changed
Expand file tree Collapse file tree 7 files changed +77
-0
lines changed Original file line number Diff line number Diff line change 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 >
Original file line number Diff line number Diff line change 1+ # Lazy Loading Images :art :
2+
3+ loading...
Original file line number Diff line number Diff line change 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+ } ) ;
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments