How to do infinite scrolling with javascript only without jquery

前端 未结 6 1020
日久生厌
日久生厌 2021-02-01 10:13

I wish to implement infinite scrolling with javascript and without jquery.

I am new to javascript.

After searching all over the net, I have this code.

         


        
6条回答
  •  情深已故
    2021-02-01 10:52

    Why whout jQuery? Some of the native properties like window.outerHeight actually can return not accurate results on some browsers. jQuery fixes that so you can rely that the methods you use returns the same results on any browser and is enough fast to use it.

    Here is a very simple way to achieve the infinite scroll without any performance impact:

    $(window).on('scroll', function() {
        var threshold = 120;
        if (window.pageYOffset > 0 && window.pageYOffset + $(window).outerHeight(false) >= $(document).outerHeight(false) - threshold) {
            // call your infinite scroll callback, like infiniteScrollDebounced($('#mytable'))
        }
    }).scroll();
    

    Notes: the condition in the if clause is intentionally like this, so if the user does not scroll, it will not calculate after window.pageYOffset > 0 and also get into the if (some micro-optimizations ;) ). The zero can be replaced with 20 or 100, so this is the threshold after the site will try to check if the user scrolls and need to do something about it.

    I use debounce to postpone the real call to load data (usually websites load data when infinite scrolls), demo: https://davidwalsh.name/function-debounce

    So I have this method:

    var infiniteScrollDebounced = _.debounce(function($table) {
        var params = $table.data('table-params');
        // Don't request any more if we have reached the end
        if (params.end)
            return;
    
        params.page++;
        params.append = true;
    
        GridHelper.reload($table, null, params);
    }, 100, true);
    

    My table have data attached to hold the current progress (page, sorting, filtering, etc) and this data is retrieved and passed into the query, so I get properly ordered and filtered results every time. GridHelper.reload() function handles the request and updates the params of the table when the data arrives (the new params are part of the response).

提交回复
热议问题