Friday, January 23, 2015

Calculate How Much Web Storage You’re Using

This is a quick one, but it’ll be a post I return to over and over again.


When you use Web storage (a.k.a. DOM storage) – localStorage or sessionStorage – to cache data, you’ll often want to know how much you’ve used already. Each browser gives you a different amount of storage to work with, and you don’t want to run out for no good reason.


You might be surprised what the sites you visit are up to these days. Cookies are old hat; they just don’t give us enough to work with, as they are capped at 4k of data each.


From Wikipedia:



Web storage provides far greater storage capacity (5 MB per origin in Google Chrome, Mozilla Firefox, and Opera; 10 MB per storage area in Internet Explorer; 25MB per origin on BlackBerry 10 devices) compared to 4 kB (around 1000 times less space) available to cookies.



If you need to know how long each browser has offered Web storage, check out the Web storage page on Can I use.


I’ve adapted some JavaScript I found out in a post on StackOverflow to display the storage used by each object in both localStorage and sessionStorage for the current origin



var storageTypes = ["localStorage", "sessionStorage"];
var x, log = [], total = 0;

for(var i=0; i < storageTypes.length; i++) {
var thisStorage = window[storageTypes[i]];
log.push("Statistics for " + storageTypes[i]);
log.push("--------------------------------");
for (x in thisStorage) {
log.push(x + " = " + ((thisStorage[x].length * 2) / 1024).toFixed(2) + "KB / " + ((thisStorage[x].length * 2) / 1024 / 1024).toFixed(2) + "MB");
total += thisStorage[x].length * 2;
};
log.push("Total = " + (total / 1024).toFixed(2) + "KB / " + (total / 1024 / 1024).toFixed(2) + "MB");
log.push("================================");
total = 0;
}
console.log(log.join("\n"));

The results will look something like those below, which I got by running the code in a console while I was on a Yammer external network.



Statistics for localStorage
--------------------------------
yj-chat-contact-list-1328414-1512241636 = 0.18KB / 0.00MB
yj-chat-contact-list-428797-1488346713 = 0.18KB / 0.00MB
Total = 0.36KB / 0.00MB
================================
Statistics for sessionStorage
--------------------------------
Total = 0.00KB / 0.00MB
================================



by Marc D Anderson via Marc D Anderson's Blog

No comments:

Post a Comment