jQuery延迟加载图像和视频无法正常工作

时间:2017-07-05 04:26:39

标签: javascript php jquery lazy-loading

我正在尝试延迟加载图片&使用jQuery的视频文件,遵循以下URL中的示例:

https://varvy.com/pagespeed/defer-videos.html

https://varvy.com/pagespeed/defer-images.html

问题是我的分页数据由jQuery加载onScroll,但我的所有图像和视频都没有加载。我该如何解决这个问题?

[分页]

$(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'); }
  }

[懒惰加载程序功能]

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;

1 个答案:

答案 0 :(得分:2)

您可以将功能与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;
    }
  });
}

在页面加载时和Ajax之后调用它

$('.blogItems').append(data);
delayMedia();

并且您的函数不是“真正”的延迟加载,通常在元素位置达到之后才出现在页面加载上

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" />