使用jQuery实现图片懒加载

1,引入jQuery库。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

2,为需要延迟加载的图片设置data-src属性。

<img src="" data-src="image.jpg" alt="图片">

3,使用jQuery监听窗口滚动事件,检测可视区域内的图片,并将其data-src属性值赋给src属性,显示图片。

$(window).scroll(function() {
  $('img[data-src]').each(function() {
    if ($(this).offset().top < $(window).scrollTop() + $(window).height()) {
      $(this).attr('src', $(this).data('src')).removeAttr('data-src');
    }
  });
});

4,初始时需调用一次,以显示页面已经在可视区域内的图片。

$('img[data-src]').each(function() {
  if ($(this).offset().top < $(window).scrollTop() + $(window).height()) {
    $(this).attr('src', $(this).data('src')).removeAttr('data-src');
  }
});

通过这些步骤,就可以实现图片的懒加载效果。需要注意的是,在jQuery中,data()方法可以获取一个元素上所有以"data-"开头的属性,并且可以通过传递参数修改相应的属性值。

posted @ 2023-05-06 17:21  神经蛙  阅读(518)  评论(0编辑  收藏  举报