如何使用原生JavaScript实现无限滚动?

How to implement infinite scroll using native JavaScript?

如何在我的项目没有任何库或框架的情况下实现infinite/endless滚动(如 Facebook)?

几乎所有指南都展示了如何使用 jQueryReactAngular 执行此操作,但我想要一个用于无限滚动的本机 JavaScript 实现。

这是用原生 JavaScript 编写的 infinite/endless 滚动代码片段:

window.onscroll = function () {
    if (window.scrollY > (document.body.offsetHeight - window.outerHeight)) {
        console.log("It's working!");                            
    }
}

要为这个函数执行添加延迟(如果你向服务器发送请求,这是必须的)你可以这样写:

window.onscroll = infiniteScroll;

    // This variable is used to remember if the function was executed.
    var isExecuted = false;

    function infiniteScroll() {
        // Inside the "if" statement the "isExecuted" variable is negated to allow initial code execution.
        if (window.scrollY > (document.body.offsetHeight - window.outerHeight) && !isExecuted) {
            // Set "isExecuted" to "true" to prevent further execution
            isExecuted = true;

            // Your code goes here
            console.log("Working...");

            // After 1 second the "isExecuted" will be set to "false" to allow the code inside the "if" statement to be executed again
            setTimeout(() => {
                isExecuted = false;
            }, 1000);
        }
    }

我在我的 ASP.NET MVC 5 项目中使用它,它非常有用。

注: 此代码片段在某些浏览器上不起作用(我在看你的 IE)。 window.scrollY 属性 在 IE 上是 undefined