HTML5 Five types of client-side offline storage solutions

Source: Internet
Author: User
Tags createindex

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 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/

 function  Save (Datamodel) {var value =  datamodel.serialize ();    window.localstorage[' datamodel ' =  value;    window.localstorage[' datacount ' =  datamodel.size ();    Console.log (datamodel.size () + ' datas is saved ' ); return  value;} function  Restore (datamodel) {var value = window.localstorage[' Datamodel ' ]; if  (value) { Datamodel.deserialize (value); Console.log (window.localstorage[' datacount ') + ' datas is restored ' ); return  value;} return ' ;} function  Clear () {if (window.localstorage[' Datamodel ' ]) {console.log (window.localstorage[' datacount ') + ' Datas is 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:

functionGetcookievalue (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; } returnUnescape (document.cookie.substring (Start, end)); }} ' return ';} function  Save (Datamodel) {var value =  datamodel.serialize (); document.cookie = ' datamodel= ' +  Escape (v Alue); Document.cookie = ' datacount= ' +  datamodel.size (); Console.log (datamodel.size () + ' datas is saved ' ); return  value;} function  Restore (datamodel) {var value = getcookievalue (' Datamodel ' ), if  (value) { Datamodel.deserialize (value); Console.log (Getcookievalue (' datacount ') + ' datas is restored ' ); return  value;} return ' ;} function  Clear () {if (Getcookievalue (' Datamodel ' )) {Console.log (Getcookievalue (' datacount ') + ' datas is Cleared ' ); Document.cookie = "datamodel=; Expires=thu, 1970 00:00:00 UTC "; document.cookie =" datacount=; Expires=thu, 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;}; functionSave (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 is saved '); }; ReturnDatamodel.serialize ();} functionRestore (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); 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 ' ;} function  Clear () {var tx = Db.transaction ("meters", "ReadWrite" ), var store = Tx.objectstore ("meters" ) ; var req =  store.opencursor (), var count = 0 , req.onsuccess = function  (event) {var res =  Event.tar Get.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) {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 is saved ');}; v Ar 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.deseri Alize (Reader.result); Console.log (datamodel.size () + ' datas is 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.