google reader load on scroll
捲軸拉到底部之後才載入接下來的資料。
有時候沒事做想寫寫程式,但又不是每次都有靈感,漸漸覺得自己的想像力愈來愈貧乏了…ㄟ,離題了,總之,沒有靈感就上 google瞧瞧吧,十之八九會找到某些有趣的功能。
google reader是我最常使用的 google服務之一,這次自己找的作業是動態載入:捲軸拉到底部之後才載入接下來的資料。想了一下會遇到什麼問題:
- 怎麼判斷拉到底部
- 用 AJAX去要資料
- 把資料塞進頁面之後(DOM),如果要掛 JavaScript事件上去應該要注意一下
codes speak louder than words. XD
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style>
.testScroll{width:200px; height:100px; border:1px solid blue;overflow-y:scroll;}
</style>
</head>
<body>
<div class='testScroll'>
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
</div>
<div class='testScroll'></div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.fn.scrollLoad=function(url, preLoad){
var preLoad=preLoad || true;
return this.each(function(){
var $panel=$(this);
//若 scrollHeight < panel 初始高度 → 載入資料,撐高 scrollHeight;
//避免意外,最多載入五次。
var loadTimes=5, initHeight=this.scrollHeight;
while(preLoad && loadTimes-- && initHeight<=$panel.height()){
initHeight=load($panel);
}
//綁 scroll事件
/*
很單純……?我本來也是這麼想的,firefox寫完很正常;
手癢開了 IE8……發現捲一下 會觸發個好幾次scroll = =a
*/
$(this).scroll(function(){
if(this.scrollTop+$panel.height()>=(this.scrollHeight-10)){
//load($panel);
laterCall(load,50,$panel);
}
});
//內部使用
var loadTimes=1;
function load($pan){
$.get(url,function(data,status){
if(status=='success'){
$pan.append('<div style="background:#cff">loadTimes:'+(loadTimes++)+'</div>');
$pan.append($(data)).find('div')
.click(function(){
alert('kk');
//這算作弊嗎?科科…jQuery的selector太隨性了…
//當然請記得產生了太多匿名函數會影響效率
});
}
else alert('error while loading');
return $pan[0].scrollHeight;
});
}
//短時間( < delayTime )觸發太多次,只執行最後一次
var laterCall=(function(){
var timer=null;
return function(fn, delayTime){
var arg=Array.prototype.slice.call(arguments,2);
if(timer!=null){
clearTimeout(timer);
timer=null;
}
timer=setTimeout(function(){
fn.apply(null,arg);
}, delayTime)
}
})()
})
};
$('.testScroll').scrollLoad('sampleData.txt');
/* sampleData.txt:
<div style='background:#cfc'>test1</div>
<div>test</div>
<div>test</div>
<div>test</div>
<div style='background:#fcc'>test2</div>
<div>test</div>
<div>test</div>
<div>test</div>
<div style='background:#ccf'>test3</div>
*/
/* 寫成 extend之前的寫法
$('.testScroll').scroll(function(){
if(this.scrollTop+$(this).height()>=(this.scrollHeight-5)){
$div=$(this);
$.get('sampleData.txt',function(data,status){
$div.append(data);
});
}
});
//*/
});
</script></html>
測試檔案 scrollLoad.rar