Last active
January 2, 2016 22:39
-
-
Save creamidea/8371414 to your computer and use it in GitHub Desktop.
LUR javascript 实现。浏览器一种缓存机制 AJAX HACKS P.390
This file contains hidden or 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
var cache = new Array; | |
var top_key = null; // 用于指向头部 | |
var prev_key = null; //用于指向最后一个元素 | |
var curr_cache_size = 0; //用于计数现在的缓存大小 | |
var MAX_CACHE_SIZE; | |
function show_cache_info(answer_form) { | |
var divCache = document.getElementById("divCacheContents"); | |
var curr_key = top_key; | |
while(curr_key != null) { | |
divCache.innerHTML = divCache.innerHTML | |
+ "KEY:" + curr_key; | |
curr_key = cache[curr_key].next; | |
} | |
// do another thing | |
} | |
function async_cmd(url, parms, divname) { | |
// do another thing | |
//检测是否在缓存中 | |
var cache_key = url + parms; // 生成cache_key | |
if (cache[cache_key]) { // 说明在缓存中 | |
// anthor things | |
// 维护链表 | |
if (cache_key != prev_key) { // 被检测元素不是最后一个,否则说明就是最后一个元素 | |
var curr_key = top_key; | |
if (cache_key != top_key) { // 说明不是第一个元素 | |
// 找到被检测元素的前一个元素 | |
while (cache[curr_key].next != cache_key) { | |
curr_key = cache[curr_key].next; | |
} | |
} else { // 说明是第一个元素 | |
top_key = cache[top_key].next; | |
} | |
// 将前一个元素指向cache[cache_key]当前指向的节点 | |
cache[curr_key].next = cache[cache_key].next; | |
// 将被检测元素移动到最后 | |
cache[prev_key].next = cache_key; | |
cache[cache_key].next = null; | |
prev_key = cache_key; | |
} | |
// do another thing | |
} else { // 没有被缓存 | |
// do another thing | |
if (curr_cache_size >= MAX_CACHE_SIZE) { // 超过缓存大小 | |
var oldest = top_key; | |
top_key = cache[oldest].next; | |
delete cache[oldest]; | |
} else { | |
curr_cache_size++; | |
} | |
if (top_key == null) { // 说明是刚刚开始创建 | |
top_key = cache_key; | |
} | |
if (prev_key != null) { // prev_key 为空说明是刚刚创建,则什么也不做。否则将元素放到最后 | |
cache[prev_key].next = cache_key; | |
} | |
// 将新增缓存放入链表 | |
cache[cache_key] = {value: response, next: null}; | |
prev_key = cache_key; | |
// do another thing | |
} | |
// do another thing | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment