commit d51f3ae0d034b51d80caf707f4929cd9a8b1927a Author: tparnell Date: Thu May 23 11:26:46 2019 -0400 init diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..90164e1 --- /dev/null +++ b/Readme.md @@ -0,0 +1,3 @@ +## Lazy loading images + +A simple example of lazy loading images \ No newline at end of file diff --git a/car.png b/car.png new file mode 100644 index 0000000..da98533 Binary files /dev/null and b/car.png differ diff --git a/index.html b/index.html new file mode 100644 index 0000000..682f1c1 --- /dev/null +++ b/index.html @@ -0,0 +1,14 @@ + + + + + + + HI + + +

Image

+ + + + \ No newline at end of file diff --git a/lazyLoad.js b/lazyLoad.js new file mode 100644 index 0000000..edfc769 --- /dev/null +++ b/lazyLoad.js @@ -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; + } + }); +} \ No newline at end of file