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.


 * 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
			url: '/path/to/content',
			data: 'page_num=' + num,
			success: function(content) {
				//Save the cache, so next time no request is needed.,'page' + num);

				//Load the content
	//Cache hit, load the content immediately
	} else {

	//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

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.