• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
擦肩没过
博客园    首页    新随笔    联系   管理    订阅  订阅
Javascript LRU Cache

Introduction

Just a simple LRU cache written in javascript. It is loosely based on ASP.NET's Cache, and includes many caching options such as absolute expiration, sliding expiration, cache priority, and a callback function. It can be used to cache data locally in the user's browser, saving a server roundtrip in AJAX heavy applications.

Download

  • Download cache.js

How It Works

 

// Create a new cache item   
// The constructor accepts an optional integer    
// parameter which places a limit on how many    
// items the cache holds   
var cache = new Cache();   
  
// add an item to the cache   
// parameters: key - the key to refer to the object   
//             value - the object to cache   
//             options - an optional parameter described below   
// the last parameter accepts an object which controls various caching options:   
//      expirationAbsolute: the datetime when the item should expire   
//      expirationSliding: an integer representing the seconds since   
//                         the last cache access after which the item   
//                         should expire   
//      priority: How important it is to leave this item in the cache.   
//                You can use the values CachePriority.Low, .Normal, or    
//                .High, or you can just use an integer.  Note that    
//                placing a priority on an item does not guarantee    
//                it will remain in cache.  It can still be purged if    
//                an expiration is hit, or if the cache is full.   
//      callback: A function that gets called when the item is purged   
//                from cache.  The key and value of the removed item   
//                are passed as parameters to the callback function.   
cache.setItem("A", "1", {expirationAbsolute: null,    
                         expirationSliding: 60,    
                         priority: CachePriority.High,   
                         callback: function(k, v) { alert('removed ' + k); }   
                        });   
                           
// retrieve an item from the cache   
// takes one parameter, the key to retreive   
// returns the cached item   
cache.getItem("A");   
  
// clears all items from the cache   
cache.clear();   

Example

Create a new cache
Size:
Add an item to the cache
Key:
Value:
Absolute Expiration:
Sliding Expiration: (s)
Priority:
Callback:
Get item from cache
Key:
Clear the cache  

posted on 2010-01-13 15:52  擦肩没过  阅读(694)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3