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

前端 未结 4 1442
灰色年华
灰色年华 2020-12-02 19:10

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

Just like Jquery Image loading http://www.appelsiini.net/projects/lazyload that is valid only for ima

相关标签:
4条回答
  • 2020-12-02 19:19

    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 onscroll events (in most browsers you won't see this, most of the time).

    $(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.

    0 讨论(0)
  • 2020-12-02 19:28

    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 src attribute.

    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 after the user has finished scrolling, by which time they will already have seen the blank content.

    0 讨论(0)
  • 2020-12-02 19:34

    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:

    $(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:

    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!!

    0 讨论(0)
  • 2020-12-02 19:41

    You may consider way point library :)

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

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

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

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

    0 讨论(0)
提交回复
热议问题