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

前端 未结 4 1568
灰色年华
灰色年华 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.

提交回复
热议问题