0
localStorage lightning talk!
b l
What is localStorage?
- Available in most modern browsers
- Stores and persists data in browser
- Associated with your url
- Accessed via Javascript
Contrived Example : app.js
$(function(){
var message = 'test' + Math.random();
localStorage.setItem('message', message);
var stored = localStorage.getItem('message');
console.assert( stored === message);
});
Putting things into storage
- Stored as key value pairs
- Anything can be overwritten
- Store as String
- JSON is handy
- localStorage.setItem('key', 'value');
Getting things from Storage
- Expect a string or undefined
- Test your results
- JSON is handy
- localStorage.getItem('key');
Contrived JSON Example
$(function(){
var numbers = {one: 'one', two: 2};
var string = JSON.stringify(object);
localStorage.setItem('numbers', string);
string = localStorage.getItem('numbers');
stored = JSON.parse(string);
console.assert(stored === numbers);
});
JSON methods
- Stringify
- Parse
- Allows storage of complex objects
- Recognised standard
- ideal analog for mongodb or similar
Use Cases
- Phonegap
- Mobile sites
- User Settings
- Disposable information
- Fonts!
Thoughts on usage
- Doesn't persist between devices
- Might need syncing with remote storage
- Expect data to be lost
- Don't store passwords
- 5Mb limits, strings only people!
Manifest files
- Handle caching
- Cache assets for offline usage
- Gives you confidence for referring to files in localStorage
- Think of it as a local CDN!
Contrived Manifest example
CACHE MANIFEST
index.html
stylesheet.css
images/logo.png
scripts/main.js
Controversy
- Hard Disk Fillertm
- 5MB per domain
- Infinite domains
- Full hard drive!
Disadvantages
- Searching isn't as neat as a DB
- Handle IE7 exceptions
- Syncing multiple devices
- Could read/wipe all localstorage with a bookmarklet!
Advantages
- Lightning fast
- No http requests for data
- Reduces load on remote storage
- Great for offline
- Widely supported
- Easy API, feels like a JS object!
Questions?
@atleastimtrying