Reputation: 139
I'm trying to lazy-load an image & video file with jQuery, following the example from the URL below:
https://varvy.com/pagespeed/defer-videos.html
https://varvy.com/pagespeed/defer-images.html
The problem is that my paginated data loaded onScroll
by jQuery, but all of my image and video wasn't loaded. How can I solve this?
[ Pagination ]
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
page += 1;
if (page <= maxPages) {
$.ajax({
beforeSend: function () {
$('.loader').html('Loading....');
},
type: 'GET',
url: 'blog/postloader?page=' + page,
data: { 'page': page },
cache: false,
success: function (data) {
$('.loader').html('Load More...');
$('.blogItems').append(data);
}
});
}
else { $('.loader').html('No More Post Available'); }
}
[ Lazy Loader function ]
function delayImg() {
var imgDefer = document.getElementsByTagName('img');
for (var i = 0; i < imgDefer.length; i++) {
if (imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src'));
}
}
}
//window.onload = delayImg;
// Lazy Load Video
function delayVid() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i = 0; i < vidDefer.length; i++) {
if (vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src', vidDefer[i].getAttribute('data-src'));
}
}
}
//window.onload = delayVid;
function start() {
delayImg();
delayVid();
}
window.onload = start;
Upvotes: 3
Views: 1743
Reputation: 19154
you can combine the function with jQuery
function delayMedia() {
$('img, iframe').each(function() {
if (!$(this).attr('src')) { // set only if src is empty
var dataSrc = $(this).data('src');
if (dataSrc)
this.src = dataSrc;
}
});
}
call it on page load and after Ajax
$('.blogItems').append(data);
delayMedia();
And your function are not "really" lazy load, usually it appear after element position reached not on page load
function isVisible(el) {
var rect = el.getBoundingClientRect(),
elemTop = rect.top,
elemBottom = rect.bottom;
return (elemTop >= 0) && (elemBottom <= window.innerHeight);
}
function delayMedia() {
$('img, iframe').each(function() {
if (!$(this).attr('src')) { // set only if src is empty
var dataSrc = $(this).data('src');
if (dataSrc && isVisible(this)){
console.log(dataSrc)
this.src = dataSrc;
}
}
});
}
$(window).on('scroll', function() {
delayMedia();
});
.dh {
height: 300px;
display: block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="dh">scroll</p>
<img src="" data-src="https://www.planwallpaper.com/static/images/1712173free-wallpaper.jpg" />
<p class="dh">scroll</p>
<img src="" data-src="https://www.planwallpaper.com/static/images/3d_falling_leaves.jpg" />
<p class="dh">scroll</p>
<img src="" data-src="https://www.planwallpaper.com/static/images/free-wallpapers-640x400.jpg" />
Upvotes: 2