Skip to content

Commit c25ae9b

Browse files
committed
Sidebar: Improve performance for reize listener
1 parent 4192bcb commit c25ae9b

File tree

1 file changed

+22
-25
lines changed

1 file changed

+22
-25
lines changed

assets/js/sidebar-v2.js

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -37,29 +37,26 @@ document.addEventListener('click', (e) => {
3737
}
3838
});
3939

40-
document.addEventListener('DOMContentLoaded', () => {
41-
const sidebar = document.querySelector('.sidebar__ul');
42-
43-
if (!sidebar) return;
44-
45-
const activeLink = sidebar.querySelector('.sidebar__link--current');
46-
47-
if (activeLink) {
48-
activeLink.scrollIntoView({
49-
behavior: 'auto',
50-
block: 'center',
51-
inline: 'nearest',
52-
});
53-
}
54-
});
55-
56-
window.addEventListener('resize', () => {
57-
const sidebar = document.getElementById('sidebar-v2');
40+
const debounce = (callback, wait) => {
41+
let timeoutId = null;
42+
return (...args) => {
43+
window.clearTimeout(timeoutId);
44+
timeoutId = window.setTimeout(() => {
45+
callback(...args);
46+
}, wait);
47+
};
48+
};
49+
50+
window.addEventListener(
51+
'resize',
52+
debounce(() => {
53+
const sidebar = document.getElementById('sidebar-v2');
5854

59-
if (
60-
window.innerWidth > 88 * 16 &&
61-
sidebar.classList.contains('sidebar__mobile-open')
62-
) {
63-
sidebar.classList.remove('sidebar__mobile-open');
64-
}
65-
});
55+
if (
56+
window.innerWidth > 88 * 16 &&
57+
sidebar.classList.contains('sidebar__mobile-open')
58+
) {
59+
sidebar.classList.remove('sidebar__mobile-open');
60+
}
61+
}, 200)
62+
);

0 commit comments

Comments
 (0)