Simple Javascript Cache

Javascript CacheModern 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.

To know when the next article is published, please subscribe to new articles using your Email below or follow me on Twitter.

Subscribe to Blog via Email

Enter your email address to receive notification about new posts.

  • http://orip.org Ori Peleg

    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 :)

  • http://orip.org Ori Peleg

    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 :)

  • http://atern.us Kiril Reznik

    It’s probably better to take out the function declaration of loadPage() to the outer scope or it will be redeclared every time getPage() is run.