Skip to content

Commit 9caf2be

Browse files
committed
feat(pat scroll-box): Optimize performance.
Optimize performance by grouping together DOM manipulation calls. The browser is now able to better optimize the code in regard to the reflow/repaint cycles. Also see: https://areknawo.com/dom-performance-case-study/
1 parent b226aeb commit 9caf2be

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

src/pat/scroll-box/scroll-box.js

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -58,34 +58,45 @@ export default Base.extend({
5858
set_scroll_classes() {
5959
const scroll_pos = this.get_scroll_y();
6060
const el = this.el;
61-
el.classList.remove("scroll-up");
62-
el.classList.remove("scroll-down");
63-
el.classList.remove("scrolling-up");
64-
el.classList.remove("scrolling-down");
65-
el.classList.remove("scroll-position-top");
66-
el.classList.remove("scroll-position-bottom");
61+
62+
const to_add = [];
6763

6864
if (scroll_pos < this.last_known_scroll_position) {
69-
el.classList.add("scroll-up");
70-
el.classList.add("scrolling-up");
65+
to_add.push("scroll-up");
66+
to_add.push("scroll-up");
67+
to_add.push("scrolling-up");
7168
} else if (this.last_known_scroll_position < scroll_pos) {
72-
el.classList.add("scroll-down");
73-
el.classList.add("scrolling-down");
69+
to_add.push("scroll-down");
70+
to_add.push("scrolling-down");
7471
}
7572

7673
if (scroll_pos === 0) {
77-
el.classList.add("scroll-position-top");
74+
to_add.push("scroll-position-top");
7875
} else if (
7976
this.scroll_listener === window &&
8077
window.innerHeight + scroll_pos >= el.scrollHeight
8178
) {
82-
el.classList.add("scroll-position-bottom");
79+
to_add.push("scroll-position-bottom");
8380
} else if (
8481
this.scroll_listener !== window &&
8582
el.clientHeight + scroll_pos >= el.scrollHeight
8683
) {
87-
el.classList.add("scroll-position-bottom");
84+
to_add.push("scroll-position-bottom");
8885
}
86+
87+
// Keep DOM manipulation calls together to let the browser optimize reflow/repaint.
88+
// See: https://areknawo.com/dom-performance-case-study/
89+
90+
el.classList.remove(
91+
"scroll-up",
92+
"scroll-down",
93+
"scrolling-up",
94+
"scrolling-down",
95+
"scroll-position-top",
96+
"scroll-position-bottom"
97+
);
98+
el.classList.add(...to_add);
99+
89100
this.last_known_scroll_position = scroll_pos;
90101
},
91102

0 commit comments

Comments
 (0)