The recent toss HTML5 game needs the offline storage function, has studied several kinds of HTML5 storage methods currently available, based on the HT for Web wrote a comprehensive example, using the cookie, WebStorage, INDEXEDDB and filesystem four kinds of local offline storage methods, the gas monitoring system of the meter position, direction, switch and table values and other information to do a curd access operation.
Http://www.hightopo.com/guide/guide/core/serialization/examples/example_exportimport.html
HTML5 storage also has a web SQL database way, although there are browser support, is the only relational database structure of storage, but the web and stop its maintenance and development, so here we no longer introduce it: beware. This specification was no longer in active maintenance and the WEB applications working Group does not intend to maintain I T further.
The whole example is to serialize and deserialize the Datamodel data model information for the HT for Web, which is simple by datamodel.serialize () serializing the model to a JSON string. The JSON string memory is deserialized out of the model information through Datamodel.deserialize (jsonstring), and the storage is primarily done for JSON strings.
First introduce the simplest storage method Localstorage, code as follows, almost no introduction is Key-value simple key value to the storage structure, WEB storage in addition to localstorage persistent storage, There are also sessionstorage for this reply, generally localstorage is more commonly used, more can refer to http://www.w3.org/tr/webstorage/
Function save (Datamodel) { var value = datamodel.serialize (); window.localstorage[' Datamodel '] = value; window.localstorage[' Datacount '] = datamodel.size (); console.log ( Datamodel.size () + ' datas are saved '); return value;} Function restore (Datamodel) { var value = window.localstorage[' Datamodel ']; if (value) { datamodel.deserialize (value); console.log ( window.localstorage[' datacount '] + ' datas are restored '); return value; } return ';} Function clear () { if (window. localstorage[' Datamodel ') { console.log (window.localStorage[') Datacount '] + ' datas are cleared '); delete window.localstorage[' Datamodel ']; delete window.localstorage[' Datacount ']; } }
The oldest storage method is a cookie, in this case I can only save an element of information, this storage method storage is limited, only suitable for simple information storage, access interface design is extremely anti-human, in order to introduce the integrity of the HTML5 storage scheme I dropped him on the list:
Function getcookievalue (name) { if (document.cookie.length > 0) { var start = Document.cookie.indexOf (name + "="); if (start  !== -1) { start = start + name.length + 1; var end = document.cookie.indexof (";", start); if (end === -1) { end = document.cookie.length; } return unesCape (Document.cookie.substring (start, end)); } } return ';} Function save (Datamodel) { var value = datamodel.serialize (); document.cookie = ' datamodel= ' + escape (value); document.cookie = ' datacount= ' + datamodel.size (); console.log (datamodel.size () + ' datas are saved '); return value;} Function restore (Datamodel) { var value = getcookievalue (' Datamodel '); if (value) { Datamodel.deserialize (value); console.log (GetCookieValue (' Datacount ') + ' datas are restored '); return value; } return ';} Function clear () { if (Getcookievalue (' Datamodel ')) { console.log (Getcookievalue (' Datacount ') + ' datas are cleared '); document.cookie = "DataModel=; expires=Thu,  01 JAN 1970 00:00:00 UTC "; document.cookie = "DATACOUNT=; EXPIRES=THU, 01 JAN 1970 00:00:00 UTC"; }}
Now more practical and powerful storage mode for indexed Database API,INDEXEDDB can be stored structure objects, you can build key and index way to find, the current browser has gradually supported INDEXEDDB storage, its use code as follows, It is important to note that many of the INDEXEDDB operations interfaces are similar to Nodejs asynchronous callbacks, especially when the continue of the cursor is asynchronous again to the operation of the onsuccess function, so it is easier to use code that is less synchronous than Nodejs.
Request = indexeddb.open ("Datamodel"); Request.onupgradeneeded = function () { db = request.result; var store = db.createobjectstore ("meters", {keypath: "id"}); store.createindex ("By_ Tag ", " tag ", {unique: true}); store.createindex (" By_name ", " name "); };request.onsuccess = function () { db = Request.result;}; Function save (Datamodel) { var tx = db.transaction ("meters", " ReadWrite "); var store = tx.objectstore (" meters "); datamodel.each (function (data) { store.put ({ id: data.getid (), tag: data.gettag (), name: data.getname (), METERVALUE: DATA.A (' Meter.value '),  METERANGLE: DATA.A (' Meter.angle '),   P3: DATA.P3 (),             R3:  DATA.R3 (),             S3: DATA.S3 () }); }); tx.oncomplete = function () { console.log (datamodel.size () + ' datas are saved '); }; &nbsP; return datamodel.serialize ();} Function restore (Datamodel) { var tx = db.transaction ("Meters", "readonly"); var store = Tx.objectstore ("meters"); var req = store.opencursor (); var nodes = []; req.onsuccess = function () { var res = req.result; if (RES) { var value = res.value; var node = createnode (); node.setid (value.id); &nBsp; node.settag (Value.tag); node.setname (Value.name); node.a ({ ' Meter.value ': value.metervalue, ' Meter.angle ': value.meterangle });           NODE.P3 (VALUE.P3);      NODE.R3 (VALUE.R3);   NODE.S3 (VALUE.S3); Nodes.push (node); res.continue (); }else{ if ( Nodes.length) { Datamodel.clear (); nodes.foreach (function (node) { datamodel.add (node); }); console.log (datamodel.size () + ' datas are restored '); } } }; return ';} Function clear () { var tx = db.transaction ("meters", "ReadWrite "); var store = tx.objectstore (" meters "); var req = store.opencursor (); var count = 0; &nBsp;req.onsuccess = function (Event) { var res = event.target.result; if (RES) { Store.delete (res.value.id); Res.continue (); count++; }else{ console.log (count + ' datas are cleared '); } };}
Finally, the FileSystem API is equivalent to the operation of local file storage, currently supports a few browsers, and its interface standards in the development of change, For example, when I write this code, most of the literature used by Webkitstorageinfo has been replaced by Navigator.webkitpersistentstorage and navigator.webkittemporarystorage, and stored files can be Filesys Tem:http://www.hightopo.com/persistent/meters.txt ' URLs are found in chrome and can even be filesystem:http://www.hightopo.com /persistent/Similar directory access, so you can also dynamically generate images to a local file, and then through the URL of the filesystem:http:*** directly assigned to the IMG HTML element src Access, so the local storage opened a new door, I believe there will be more strange and exotic applications.
Navigator.webkitPersistentStorage.queryUsageAndQuota (function (Usage, quota) { console.log (' persistent: ' + usage + '/' + quota + ' - ' + usage / quota + '% '); }); Navigator.webkitPersistentStorage.requestQuota (2 * 1024 * 1024, function (grantedbytes) { Window.webkitrequestfilesystem (window. Persistent, grantedbytes, function (FS) { window.fs = fs; }); Function save (Datamodel) { var value = daTamodel.serialize (); fs.root.getfile (' Meters.txt ', {create: true}, function (fileentry) { console.log (FileEntry.toURL ()) ; fileentry.createwriter (function (fileWriter) { fileWriter.onwriteend = function () { console.log (datamodel.size () + ' datas are saved '); }; var blob = new blob ([value], {type: ' Text/plain '}); filewriter.write (BLOB); }); }); return value;} Function restore (Datamodel) { fs.root.getfile (' Meters.txt ', {}, function (fileentry) { fileentry.file (function ( File) { var reader = new filereader (); reader.onloadend = function (e) { datamodel.clear (); datamodel.deserialize (Reader.result); console.log (DataModel.size () + ' datas are restored '); }; Reader.readastext (file); }); }); return ';} Function clear () { fs.root.getfile (' Meters.txt ', {create: false}, function (fileentry) { fileentry.remove (function () { console.log (FileEntry.toURL () + ' is removed '); }); }); }
Browser-side storage method is still in rapid development, in addition to the above several application Cache, I believe there will be rookie, although the "cloud" is a big trend, but the client is not to go to the extreme "thin" scheme, so many years out of the client storage mode , explaining that the client more powerful market demand is strong, of course, the current turbulent phase is the client programmer, in addition to adapt to mouse and touch, but also to adapt to a variety of screens, now also have to consider suitable for a variety of storage, I hope this article can be in the selection of client storage solutions A little help, the last paragraph based on HT For web operations HTML5 Storage Example Video effects: http://v.youku.com/v_show/id_XODUzODU2MTY0.html
Http://www.hightopo.com/guide/guide/core/serialization/examples/example_exportimport.html
HTML5 Five types of client-side offline storage solutions