Skip to content

Instantly share code, notes, and snippets.

@steveosoule
Created August 8, 2019 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steveosoule/c42db23733c70f818fa676c701e34752 to your computer and use it in GitHub Desktop.
Save steveosoule/c42db23733c70f818fa676c701e34752 to your computer and use it in GitHub Desktop.
Lazyload thing with jQuery
var lazyAny = function(selector, callback, offset){
offset = isNaN(offset) ? 250 : offset;
var init = function(){
debouncedCheck();
$(window).on('load scroll resize', debouncedCheck);
};
var check = function(){
var $elements = $(selector);
var $window = $(window);
$elements.each(function(i, element){
var $element = $(element),
top_of_element = $element.offset().top - offset,
bottom_of_element = $element.offset().top + $element.outerHeight(),
bottom_of_screen = $window.scrollTop() + window.innerHeight,
top_of_screen = $window.scrollTop();
if((bottom_of_screen >= top_of_element) && (top_of_screen <= bottom_of_element)){
callback($element);
}
});
};
// https://davidwalsh.name/javascript-debounce-function
var debounce = function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
var debouncedCheck = debounce(check, 100);
init();
};
(function lazySrc(){
lazyAny('[data-src]', function($element){
$element.attr('src', $element.data('src')).removeAttr('data-src');
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment