Created
August 8, 2019 22:11
-
-
Save steveosoule/c42db23733c70f818fa676c701e34752 to your computer and use it in GitHub Desktop.
Lazyload thing with jQuery
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
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(); | |
}; |
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
(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