Created
September 11, 2014 18:42
-
-
Save hartzis/0034817feb4dda37147c to your computer and use it in GitHub Desktop.
window scroll event best practice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<title>JavaScript Patterns</title> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<script> | |
/* Title: window scroll event | |
* Description: avoid attaching handlers to the window scroll event | |
*/ | |
// antipattern | |
$(window).scroll(function () { | |
$('.foo').something(); | |
}); | |
// preferred | |
var outerPane = $details.find(".details-pane-outer"), | |
didScroll = false; | |
$(window).scroll(function () { | |
didScroll = true; | |
}); | |
setInterval(function () { | |
if (didScroll) { | |
didScroll = false; | |
// Check your page position and then | |
// Load in more results | |
// outerPane.html(); | |
} | |
}, 250); | |
// preferred v2, timeout instead of interval - no unnecessary ticks | |
var scrollTimeout; // global for any pending scrollTimeout | |
var outerPane = $details.find(".details-pane-outer"); | |
$(window).scroll(function () { | |
if (scrollTimeout) { | |
// clear the timeout, if one is pending | |
clearTimeout(scrollTimeout); | |
scrollTimeout = null; | |
} | |
scrollTimeout = setTimeout(scrollHandler, 250); | |
}); | |
scrollHandler = function () { | |
// Check your page position and then | |
// Load in more results | |
// outerPane.html(); | |
}; | |
// References | |
// http://ejohn.org/blog/learning-from-twitter/ | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$details ??