Last active
August 27, 2020 18:24
-
-
Save hellojebus/68e25c83fbee05a783ab16b60882c4db to your computer and use it in GitHub Desktop.
Lazyload function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Background Image Usage --> | |
<div data-lazyload="bg" data-lazyload-src="https://path/to/image.jpg"></div> | |
<!-- Image Usage --> | |
<img data-lazyload="img" data-lazyload-src="https://path/to/image.jpg" /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* LazyLoad background Images | |
* */ | |
$(window).on("resize scroll", function() { | |
lazyLoadBg(); | |
}); | |
lazyLoadBg(); | |
function lazyLoadBg(){ | |
$('[data-lazyload]').each(function(){ | |
var el = $(this); | |
var type = el.data("lazyload"); | |
var src = el.data("lazyload-src"); | |
//load up images 500 px before viewport | |
var viewOffset = 500; | |
if(type == "bg"){ | |
viewOffset = 0 | |
} | |
var elementTop = el.offset().top - viewOffset; | |
var elementBottom = elementTop + el.outerHeight(); | |
var viewportTop = $(window).scrollTop(); | |
var viewportBottom = viewportTop + $(window).height(); | |
var inView = elementBottom > viewportTop && elementTop < viewportBottom; | |
if(inView){ | |
if(type === "bg"){ | |
el.css('background-image','url(' + src + ')'); | |
} | |
if(type === "img"){ | |
el.attr("src", src); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment