jQuery load more data on scroll

前端 未结 9 1061
夕颜
夕颜 2020-11-22 10:44

I am just wondering how can i implement more data on scroll only if the div.loading is visible.

Usually we look for page height and scroll height, to see if we need

9条回答
  •  爱一瞬间的悲伤
    2020-11-22 11:26

    I spent some time trying to find a nice function to wrap a solution. Anyway, ended up with this which I feel is a better solutions when loading multiple content on a single page or across a site.

    Function:

    function ifViewLoadContent(elem, LoadContent)
        {
                var top_of_element = $(elem).offset().top;
                var bottom_of_element = $(elem).offset().top + $(elem).outerHeight();
                var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
                var top_of_screen = $(window).scrollTop();
    
                if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
                if(!$(elem).hasClass("ImLoaded"))   {
                    $(elem).load(LoadContent).addClass("ImLoaded");
                }
                }
                else {
                   return false;
                }
            }
    

    You can then call the function using window on scroll (for example, you could also bind it to a click etc. as I also do, hence the function):

    To use:

    $(window).scroll(function (event) {
            ifViewLoadContent("#AjaxDivOne", "someFile/somecontent.html"); 
    
            ifViewLoadContent("#AjaxDivTwo", "someFile/somemorecontent.html"); 
        });
    

    This approach should also work for scrolling divs etc. I hope it helps, in the question above you could use this approach to load your content in sections, maybe append and thereby dribble feed all that image data rather than bulk feed.

    I used this approach to reduce the overhead on https://www.taxformcalculator.com. It died the trick, if you look at the site and inspect element etc. you can see impact on page load in Chrome (as an example).

提交回复
热议问题