第四章
创建缓存层
//内存层
var memoryCache={};
var CACHE_TTL=864000000;
var CACHE_PREFIX="ti";
function setCache(mykey,data){
var stamp,obj;
stamp=Date.now();
obj={
date:stamp,
data:data
};
//localstorage层
localStorage.setItem(CACHE_PREFIX+mykey,JSON.stringify(obj));
memoryCache[CACHE_PREFIX+mykey]=obj;
}
console.log(window);
function getCached(mykey){
var key,obj;
key=CACHE_PREFIX+mykey;
if(memoryCache[key]){
if(memoryCache[key].date-Date.now()>CACHE_TTL){
return false;
}
return memoryCache[key].data;
}
obj=localStorage.getItem(key);
if(obj){
obj=JSON.parse(obj);
if(Date.now()-obj.date>CACHE_TTL){
localStorage.removeItem(key);
delete(memoryCache[key]);
return false;
}
memoryCache[key]=obj;
return obj.data;
}
}
setCache('lilu',39);
getCached('lilu');
console.log(memoryCache['tililu']);
console.log(localStorage);
管理localStorage
localStorage可以存放5MB的内容
以下公式可以计算localStorage的空间是否已经满了
1024*1024*5-unescape(encodeURIComponent(JSON.stringify(localStorage))).length
应用缓存Application Cache
<html manifest="birds.appcache">
CACHE MANIFEST
# The date below is a simple
# way to make sure I change this
#file
# 2013-03-15r4
jquery-1.8.0.min.js
gull-360x112.jpg
gull-640x360.jpg
gull-720x225.jpg
FALLBACK:
NETWORK:
*
第六章 轻触 VS 单击 :基本的事件处理
使用自定义事件
function togglePicture(){
var h=document.querySelector('.picture');
if(h.style.display=="none"){
h.style.display="block";
}else{
h.style.display="none";
}
}
window.addEventListener('tap',function(e){
togglePicture();
})
window.addEventListener('touchstart',function(e){
var tap=document.createEvent('CustomEvent');
tap.initCustomEvent('tap',true,true,null);
window.dispatchEvent(tap);
});