Skip to content

Instantly share code, notes, and snippets.

@sivagao
Created February 18, 2014 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sivagao/9079477 to your computer and use it in GitHub Desktop.
Save sivagao/9079477 to your computer and use it in GitHub Desktop.
<!doctype html>
<html lang="en">
<head>
<title>JavaScript 模式和反模式</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* 题目: 窗口滚动事件
* 描述: 不要在窗口滚动事件上附加事件处理程序
*/
// 反模式
$(window).scroll(function () {
$('.foo').something();
});
// 模式 1
// 用 setInterval 检查你的页面中的位置,再执行命令
var outerPane = $details.find(".details-pane-outer"),
didScroll = false;
$(window).scroll(function () {
didScroll = true;
});
setInterval(function () {
if (didScroll) {
didScroll = false;
// Load in more results
// outerPane.html();
}
}, 250);
// 模式 2
// 避免定期的执行,而只在滚动时执行
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();
};
// 参考
// 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