Modern web-sites and web-application make heavy use of Javascript to improve the user experience. To further improve the user experience, I’d like to propose a simple caching mechanism.
var Cache = {
stack: {}, //Cache stack
load: function(id){ //Load cache if found
return (typeof(this.stack[id]) != 'undefined') ? this.stack[id] : false;
},
save: function(data,id){ //Cache data with unique id
this.stack[id] = data;
},
remove: function(id){//Remove cache for identifier
if(typeof(this.stack[id]) != 'undefined')
delete this.stack[id];
}
};
Short and sweet. Basic usage involves calling the load() method to check for cache hit and fetching the actual data if cache is empty. The remove() method is used to force fresh data to be retrieved.
Example:
/*
* Say we want to load different pages for a paginated view via an AJAX request.
* We'll wrap the process in a function that retrieves the requested page given the page number.
*/
function getPage(num){
//We check the cache first.
var content = Cache.load('page' + num);
//If cache is empty, it will return false.
if(content == false) {
//Retrieve the cache via AJAX request using jQuery
$.get({
url: '/path/to/content',
data: 'page_num=' + num,
success: function(content) {
//Save the cache, so next time no request is needed.
Cache.save(content,'page' + num);
//Load the content
loadPage(content);
}
});
//Cache hit, load the content immediately
} else {
loadPage(content);
}
//We seperate the actual page loading due to the asynchronious nature of AJAX
function loadPage(content) {
//Load the page into a DIV with an id of 'pagecontent', using jQuery
$('div#pagecontent').html(content);
}
};
In this example I used the cache to store a string (retrieved page HTML). However, you can easily use it to store objects and arrays (JSON anyone?) for more demanding usage.




2008 - The Future
Cool!
A straight Object provides the same functionality as the ‘Cache’, but the indicative method names sure are sweet.
I’d like a ‘has’ method too,
has : function(id){ // is there a cache value?
return this.stack[id] != ‘undefined’;
}
but I guess it’s a personal preference thing.
Side note - a ‘preview’ button for the comments, and specifying the formatting allowed, would be cool
Comment by Ori Peleg — 27 May @ 2:46 am