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.
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 mode 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 more commonly used, more can refer to http://www.w3.org/TR/webstorage/
functionSave (Datamodel) {varValue =datamodel.serialize (); window.localstorage[' Datamodel '] =value; window.localstorage[' Datacount '] =datamodel.size (); Console.log (Datamodel.size ()+ ' datas is saved '); returnvalue;}functionRestore (datamodel) {varValue = window.localstorage[' Datamodel ']; if(value) {datamodel.deserialize (value); Console.log (window.localstorage[' Datacount ' + ' datas is restored '); returnvalue; } return‘‘;}functionClear () {if(window.localstorage[' Datamodel ']) {Console.log (window.localstorage[' Datacount ' + ' datas is cleared '); Deletewindow.localstorage[' Datamodel ']; Deletewindow.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:
functionGetcookievalue (name) {if(Document.cookie.length > 0) { varStart = document.cookie.indexOf (name + "="); if(Start!==-1) {Start= start + name.length + 1; varEnd = Document.cookie.indexOf (";", start); if(end = =-1) {End=document.cookie.length; } returnunescape (document.cookie.substring (Start, end)); } } return‘‘;}functionSave (Datamodel) {varValue =datamodel.serialize (); Document.cookie= ' datamodel= ' +Escape (value); Document.cookie= ' datacount= ' +datamodel.size (); Console.log (Datamodel.size ()+ ' datas is saved '); returnvalue;}functionRestore (datamodel) {varValue = Getcookievalue (' Datamodel '); if(value) {datamodel.deserialize (value); Console.log (Getcookievalue (' Datacount ') + ' datas is restored '); returnvalue; } return‘‘;}functionClear () {if(Getcookievalue (' Datamodel ') {console.log (Getcookievalue (' Datacount ') + ' datas is cleared '); Document.cookie= "datamodel=; Expires=thu, Jan 1970 00:00:00 UTC "; Document.cookie= "datacount=; Expires=thu, 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; varstore = Db.createobjectstore ("meters", {keypath: "id"}); Store.createindex ("By_tag", "tag", {unique:true}); Store.createindex ("By_name", "name"); };request.onsuccess=function() {db=Request.result;};functionSave (Datamodel) {vartx = Db.transaction ("meters", "ReadWrite"); varstore = 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 is saved '); }; returndatamodel.serialize ();}functionRestore (datamodel) {vartx = Db.transaction ("meters", "ReadOnly"); varstore = Tx.objectstore ("Meters"); varreq =store.opencursor (); varnodes = []; Req.onsuccess=function() { varres =Req.result; if(res) {varValue =Res.value; varnode =CreateNode (); Node.setid (value.id); 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 is restored '); } } }; return‘‘;}functionClear () {vartx = Db.transaction ("meters", "ReadWrite"); varstore = Tx.objectstore ("Meters"); varreq =store.opencursor (); varCount = 0; Req.onsuccess=function(event) {varres =Event.target.result; if(res) {store.Delete(res.value.id); Res.Continue(); Count++; }Else{Console.log (Count+ ' datas is 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; }); });functionSave (Datamodel) {varValue =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 is saved '); }; varBlob =NewBlob ([value], {type: ' Text/plain ')}); Filewriter.write (BLOB); }); }); returnvalue;}functionRestore (Datamodel) {fs.root.getFile (' Meters.txt ', {},function(fileentry) {fileentry.file (function(file) {varReader =NewFileReader (); Reader.onloadend=function(e) {datamodel.clear (); Datamodel.deserialize (Reader.result); Console.log (Datamodel.size ()+ ' datas is restored '); }; Reader.readastext (file); }); }); return‘‘;}functionClear () {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
HTML5 WEB Client Summary of five offline storage methods