Skip to content

Commit

Permalink
perf: add throttle for scroll and resize listener
Browse files Browse the repository at this point in the history
  • Loading branch information
reuixiy committed Mar 6, 2020
1 parent fae1f2a commit 6945afd
Show file tree
Hide file tree
Showing 6 changed files with 46 additions and 9 deletions.
9 changes: 6 additions & 3 deletions assets/js/back-to-top.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
const backToTop = document.getElementById('back-to-top');

if (backToTop !== null) {
window.addEventListener('scroll', function() {
window.scrollY > 100 ? backToTop.classList.add('show') : backToTop.classList.remove('show');
});
window.addEventListener(
'scroll',
throttle(function() {
window.scrollY > 100 ? backToTop.classList.add('show') : backToTop.classList.remove('show');
}, delayTime)
);
}
24 changes: 24 additions & 0 deletions assets/js/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// https://www.30secondsofcode.org/js/s/throttle/

const throttle = (fn, wait) => {
let inThrottle, lastFn, lastTime;
return function() {
const context = this,
args = arguments;
if (!inThrottle) {
fn.apply(context, args);
lastTime = Date.now();
inThrottle = true;
} else {
clearTimeout(lastFn);
lastFn = setTimeout(function() {
if (Date.now() - lastTime >= wait) {
fn.apply(context, args);
lastTime = Date.now();
}
}, Math.max(wait - (Date.now() - lastTime), 0));
}
};
};

const delayTime = 420;
16 changes: 13 additions & 3 deletions assets/js/nav-toggle.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,19 @@ navCurtain.addEventListener('animationend', (e) => {

// Close nav when window is scrolled or resized by user

window.addEventListener('scroll', closeNav);

window.addEventListener('resize', closeNav);
window.addEventListener(
'scroll',
throttle(function() {
closeNav();
}, delayTime)
);

window.addEventListener(
'resize',
throttle(function() {
closeNav();
}, delayTime)
);

function closeNav() {
if (navToggle.checked) {
Expand Down
2 changes: 1 addition & 1 deletion assets/scss/components/_back-to-top.scss
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

@if ($enableBackToTopAutoHide) {
.back-to-top {
bottom: -5em;
bottom: -3.6em;
transition: bottom 0.3s ease-in-out;
&.show {
bottom: 0;
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"Target":"css/meme.min.fee27c7492b717ad2200531e61fca428c2153b6479073d07250c50c33b5c2604.css","MediaType":"text/css","Data":{"Integrity":"sha256-/uJ8dJK3F60iAFMeYfykKMIVO2R5Bz0HJQxQwztcJgQ="}}
{"Target":"css/meme.min.becf25eee993457d079cf9cb1933804875c3ac89960278e671d97ba4930e4ce6.css","MediaType":"text/css","Data":{"Integrity":"sha256-vs8l7umTRX0HnPnLGTOASHXDrImWAnjmcdl7pJMOTOY="}}

0 comments on commit 6945afd

Please sign in to comment.