Skip to content

Instantly share code, notes, and snippets.

@xlawok
Created September 16, 2021 07:01
Show Gist options
  • Save xlawok/f5d0c158113aa51435e60a8f9e7542ef to your computer and use it in GitHub Desktop.
Save xlawok/f5d0c158113aa51435e60a8f9e7542ef to your computer and use it in GitHub Desktop.
images lazy load
(function ($) {
var lazy_images_elements = [].slice.call(document.querySelectorAll("[data-lazy-src]"));
if ("IntersectionObserver" in window) {
var lazy_src_observer = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
var $lazy = $(entry.target);
$lazy.attr("src", $lazy.attr("data-lazy-src"))
.attr("srcset", $lazy.attr("data-lazy-srcset"))
.attr("data-lazy-src", null)
.attr("data-lazy-srcset", null);
lazy_src_observer.unobserve(entry.target);
}
});
});
lazy_images_elements.forEach(function(element){
lazy_src_observer.observe(element);
});
} else {
// todo: fallback if no IntersectionObserver
}
lazy_images_elements = [];
$(function () {
// observe_lazy_images($("[data-lazy-src]"));
var $lazy_css_backgrounds = $(".lazy-image");
if ("IntersectionObserver" in window) {
var lazy_css_observer = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
$(entry.target).addClass("lazy-visible");
}
});
});
$lazy_css_backgrounds.each(function () {
lazy_css_observer.observe(this);
})
} else {
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment