Should addFillGapSelector check if a selector is already present?
Paul-Hebert opened this issue ยท 3 comments
Thanks for the great library! It's a lifesaver and I've used it for multiple projects!
I ran into an issue and was wondering if we could make a change to fix it.
The Problem
I'm building out a complex interface where the small screen and large screen experiences are very different. On large screens an element should have a fill gap selector. On small screens it should not. I had a function that looked roughly like this:
updateScrollLock() {
if(isLargeScreen) {
scrollLock.addFillGapSelector('.foo');
} else {
scrollLock.removeFillGapSelector('.foo');
}
if(lockScrolling) {
scrollLock.disableScrolling();
} else {
scrollLock.enableScrolling();
}
}
This function would be called whenever a user opened or closed a menu. This action could happen a number of times. At first the menu opening and closing was snappy, but over time I noticed that the performance degraded on large screen lower-power machines (and in low performing browsers).
I dug into it and realized that every time the menu was toggled the fill gap selector was being re-added so that state.fillGapSelectors
looked like this: ['.foo', '.foo', '.foo', ...]
. I think this was slowing down performance, since when scroll locking was toggled it had to iterate over all those duplicate selectors and make changes.
A Quick Fix
I was able to work around it by doing something like this:
scrollLock.addFillGapSelector('.foo');
-->
scrollLock.removeFillGapSelector('.foo');
scrollLock.addFillGapSelector('.foo');
This works fine but it would be nice if it was impossible to get into this situation in the first place.
A Fix in the Library
We could avoid this by doing something like this:
export const addFillGapSelector = (selector) => {
if (selector) {
const selectors = argumentAsArray(selector);
selectors.map((selector) => {
if(state.fillGapSelectors.indexOf(selector) !== -1) {
state.fillGapSelectors.push(selector);
if (!state.scroll) {
fillGapSelector(selector);
}
}
});
}
};
I'd be happy to put up a PR if this makes sense to you.
Hey. Thanks I am very pleased ๐
Yeah, you can make PR if you want, that would be very helpful.
Awesome, will do! I'll try to get to this on Monday