Javascript 每当 DIV 第一次可见时加载(延迟加载)一个 Div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8192651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:03:06  来源:igfitidea点击:

Load (Lazy Loading) a Div whenever the DIV gets visible for the first time

javascriptjquery

提问by Moons

I want to enable a lazy loading for the contents of my website.

我想为我的网站内容启用延迟加载。

Just like Jquery Image loading http://www.appelsiini.net/projects/lazyloadthat is valid only for images.

就像 Jquery 图像加载http://www.appelsiini.net/projects/lazyload仅对图像有效。

I want to do it for the content (DIV's).

我想为内容(DIV)做这件事。

Suppose we have a long page then i want to download the div as they becomes visible.

假设我们有一个很长的页面,那么我想在 div 变得可见时下载它们。

I will download the content using JSON or PageMethods. But i want the code that will execute the function for loading contents.

我将使用 JSON 或 PageMethods 下载内容。但我想要执行加载内容函数的代码。

So whether we can somehow find this that div is visible only scrolling down.

所以我们是否能以某种方式找到这个 div 只有向下滚动才能看到。

Means i need to use some scroll events but dont know how.

意味着我需要使用一些滚动事件但不知道如何使用。

Any help is appreciated.

任何帮助表示赞赏。

采纳答案by Oroboros102

The code below does not cover cases where the user scrolls up from the bottom (read patrick's comment below). Also, it allows multiple event executions because of several concurrent onscrollevents (in most browsers you won't see this, most of the time).

下面的代码不包括用户从底部向上滚动的情况(阅读下面 patrick 的评论)。此外,由于多个并发onscroll事件,它允许多个事件执行(在大多数浏览器中,大多数情况下您不会看到这一点)。

$(document).ready(function(){
    $(window).scroll(function() {
        //check if your div is visible to user
        // CODE ONLY CHECKS VISIBILITY FROM TOP OF THE PAGE
        if ($(window).scrollTop() + $(window).height() >= $('#your_element').offset().top) {
            if(!$('#your_element').attr('loaded')) {
                //not in ajax.success due to multiple sroll events
                $('#your_element').attr('loaded', true);

                //ajax goes here
                //in theory, this code still may be called several times
            }
        }
    });
});

Proper solution, that takes into consideration scrolling from bottom here.

正确的解决方案,即考虑到滚动自下而上这里

回答by patrick

I was looking for this to load advertising from my openX server only when the advertising should be visible. I'm using the iFrame version of openX which is loaded in a div. The answer here put me on my way to solving this problem, but the posted solution is a bit too simple. First of all, when the page is not loaded from the top (in case the user enters the page by clicking 'back') none of the divs are loaded. So you'll need something like this:

我一直在寻找它来仅在广告应该可见时从我的 openX 服务器加载广告。我正在使用加载在 div 中的 iFrame 版本的 openX。这里的答案让我开始解决这个问题,但发布的解决方案有点太简单了。首先,当页面未从顶部加载时(以防用户通过单击“返回”进入页面),不会加载任何 div。所以你需要这样的东西:

$(document).ready(function(){
   $(window).scroll(lazyload);
   lazyload();
});

Also, you'll need to know what defines a visible div. That can be a div that's fully visible or partially visible. If the bottom of the object is greater or equal to the top of the window AND the top of the object is smaller or equal to the bottom of the window, it should be visible (or in this case: loaded). Your function lazyload()might look like this:

此外,您需要知道什么定义了可见的 div。那可以是完全可见或部分可见的 div。如果对象的底部大于或等于窗口的顶部,并且对象的顶部小于或等于窗口的底部,则它应该是可见的(或在这种情况下:加载)。您的函数lazyload()可能如下所示:

function lazyload(){
   var wt = $(window).scrollTop();    //* top of the window
   var wb = wt + $(window).height();  //* bottom of the window

   $(".ads").each(function(){
      var ot = $(this).offset().top;  //* top of object (i.e. advertising div)
      var ob = ot + $(this).height(); //* bottom of object

      if(!$(this).attr("loaded") && wt<=ob && wb >= ot){
         $(this).html("here goes the iframe definition");
         $(this).attr("loaded",true);
      }
   });
}

I tested this on all major browsers and even on my iPhone. It works like a charm!!

我在所有主要浏览器甚至我的 iPhone 上测试了这个。它就像一个魅力!

回答by Ravinder Payal

You may consider way point library :)

您可以考虑航点库:)

http://imakewebthings.com/waypoints/api/waypoint/

http://imakewebthings.com/waypoints/api/waypoint/

Its use cases and api's are defined in above link

它的用例和api在上面的链接中定义

It is of 9 kb when compressed. It will add an additional -100 ms- 50ms timelag while loading page on 3g/ 4g

压缩后为 9 kb。在 3g/4g 上加载页面时,它会增加一个额外的 -100 ms- 50ms 时滞

Edit :- It can be used standalone and it also supports all major frameworks.

编辑:- 它可以独立使用,也支持所有主要框架。

回答by Chris Haines

Here is a solution that lazy loads images when they come within 500px of view. It can be adapted to load other types of content. The images themselves have an attribute data-lazy="http://..."with the image url in it, and then we just put a dummy transparent image for the srcattribute.

这是一个在 500 像素范围内延迟加载图像的解决方案。它可以适应加载其他类型的内容。图像本身有一个属性,data-lazy="http://..."其中包含图像 url,然后我们只需为该src属性放置一个虚拟透明图像。

var pixelLoadOffset = 500;
var debouncedScroll = debounce(function () {
    var els = app.getSelector(el, 'img[data-lazy]');
    if (!els.length) {
        $(window).unbind('scroll', debouncedScroll);
        return;
    }
    var wt = $(window).scrollTop();    //* top of the window
    var wb = wt + $(window).height();  //* bottom of the window

    els.each(function () {
        var $this = $(this);
        var ot = $this.offset().top;  //* top of object
        var ob = ot + $this.height(); //* bottom of object
        if (wt <= ob + pixelLoadOffset && wb >= ot - pixelLoadOffset) {
            $this.attr('src', $this.attr('data-lazy')).removeAttr('data-lazy');
        }
    });
}, 100);
$(window).bind('scroll', debouncedScroll);

The debounce function I'm using is as follows:

我使用的去抖动功能如下:

function debounce(func, wait, immediate) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
        }, wait);
        if (immediate && !timeout) func.apply(context, args);
    };
}

You need to keep in mind that this isn't very effective on iOS, as the scroll event doesn't fire until afterthe user has finished scrolling, by which time they will already have seen the blank content.

您需要记住,这在 iOS 上不是很有效,因为滚动事件直到用户完成滚动才会触发,届时他们将已经看到空白内容。