init
This commit is contained in:
3
Readme.md
Normal file
3
Readme.md
Normal file
@@ -0,0 +1,3 @@
|
||||
## Lazy loading images
|
||||
|
||||
A simple example of lazy loading images
|
||||
14
index.html
Normal file
14
index.html
Normal file
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
||||
<title>HI</title>
|
||||
</head>
|
||||
<body>
|
||||
<H1>Image</H1>
|
||||
<img data-src="car.png" class="lazy" />
|
||||
<script src="lazyLoad.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
35
lazyLoad.js
Normal file
35
lazyLoad.js
Normal file
@@ -0,0 +1,35 @@
|
||||
if(window.IntersectionObserver) {
|
||||
document.addEventListener("DOMContentLoaded", function() {
|
||||
var lazyImages = [].slice.call(document.querySelectorAll(".lazy"));
|
||||
var lazyImageObserver = new IntersectionObserver(function(entries, observer) {
|
||||
entries.forEach(function(entry) {
|
||||
if (entry.isIntersecting) {
|
||||
var lazyImage = entry.target;
|
||||
if(lazyImage.dataset.src) {
|
||||
lazyImage.src = lazyImage.dataset.src;
|
||||
}
|
||||
if(lazyImage.dataset.srcset) {
|
||||
lazyImage.srcset = lazyImage.dataset.srcset;
|
||||
}
|
||||
|
||||
lazyImage.classList.remove("lazy");
|
||||
lazyImageObserver.unobserve(lazyImage);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
lazyImages.forEach(function(lazyImage) {
|
||||
lazyImageObserver.observe(lazyImage);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
var lazyImages = [].slice.call(document.querySelectorAll(".lazy"));
|
||||
lazyImages.forEach(function(image) {
|
||||
if(image.dataset.srcset) {
|
||||
image.srcset = image.dataset.srcset;
|
||||
}
|
||||
if(image.dataset.src) {
|
||||
image.src = image.dataset.src;
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user