Question:
I want to throttle function calls which are added as Event Listeners to the window.scroll function by a 3rd party library provided by an external supplied (cant be changed).I figured out that the library causes some overhead by its scroll event listener, because if I remove the event handler, my page runs much smoother.
As I cannot directly control or change the external JS file, I thought to read the scroll-events attached to the Window and delete / rebind them again, but in a throttled format, as I have already the Underscore.js library in use.
I’m trying to read the Scroll events and than replace the function callback as a throttled version:
jQuery(document).ready(function($) {
let scrollEvents = $._data(window, 'events').scroll;
for(evt of scrollEvents ) {
evt.handler = _.throttle(evt.handler, 200)
}
});
Does not seem to bring the appropriate improvement. In the Webdeveloper Bar “Global Event Listeners” I still see the original event listeners attached, I do NOT see the Underscore Library (as intermediate layer) listed there.What is potentially wrong with this code?
Thanks
EDIT Those events are added globally to the Window, see WebDev Screenshot:

AND
$._data(window, 'events').scroll;
shows ALL those 5 events, so jQuery should be able to change them, isnt it?Answer:
Found a beautiful solution using Underscore.js, proxying the callback functions by a Throttler before adding it as Event Handler: var f_add = EventTarget.prototype.addEventListener;
var f_remove = EventTarget.prototype.removeEventListener;
EventTarget.prototype.addEventListener = function(type, fn, capture) {
this.f = f_add;
if(type == 'scroll' && typeof _ === 'function')
fn = _.throttle(fn, 350);
this.f(type, fn, capture);
}
EventTarget.prototype.removeEventListener = function(type, fn, capture) {
this.f = f_remove;
if(type == 'scroll' && typeof _ === 'function')
fn = _.throttle(fn, 350);
this.f(type, fn, capture);
}
It overwrites the prototype for add/removeEventListener -> And if the event is a scroll event, it surrounds the Function fn
with _.throttle().If you have better answer, please add a comment about this, thank you!
Leave a Review