简体   繁体   中英

Call a function onload, and onscroll also?

I have a function which is called when the user scrolls. Works well, but for elements those are on the top of the document (and on the top of the viewport of course), the effects inside the function executes after the first scroll. I need to know if there's a way to do something like this:

if(window.onscroll || window.onload){
    function toExecute(){}
}

The easiest way to do this would be to bind the same function to both the load and the scroll event.
However, since the scroll handler is called very rapidly and can easily cause performance issues on either mobile devices or older browsers, it's better to debounce the scroll handler.

 function foo() { console.log('foo called at ' + new Date()); } let timer; function debouncedFoo() { if (timer) return; timer = setTimeout(() => { timer = null; foo(); }, 20); } window.addEventListener('load', foo); window.addEventListener('scroll', debouncedFoo); 
 body { height: 3000px; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM