I mentioned the other day that localStorage
can be used as an alternative for cookies. The benefit is that localStorage
doesn’t sent it’s data back on every request to the server like a cookie. Headers are uncompressed in HTTP making that very costly. However not every web browser out there supports localStorage
. Most however do.
Here’s an example based on jQuery and jQuery.cookie. It’s designed to turn objects into JSON and store the JSON representation. On retrieval it restores the object. This doesn’t handle things like expiring cookies (it simply defaults to 365 days). I just had this around from an old project with these very specific requirements and figured I’d post it as-is in case it can help anyone and to demonstrate. This isn’t ideal for reuse, but for someone playing with the idea, maybe it will motivate 😉 .
Pretty simple right? It’s still a key/value API.
2 replies on “localStorage With Cookie Fallback”
Chris Van of the AMO team wrote this guy: https://gist.github.com/876117 I don’t know if it automatically deserializes JSON though.
Cool… doesn’t look to me like it deserializes JSON. Normally I’d typeof to handle that, but this post is what I used on safepasswd.com to “remember” your last settings. In that use case, it’s always an object hence unnecessary.