Five offline storage solutions for HTML5 clients

Source: Internet
Author: User
Tags createindex

Five offline storage solutions for HTML5 clients

Recently, HTML5 games require offline storage, so we have studied several currently available HTML5 storage methods and written a comprehensive example based on HT for Web, using cookies, WebStorage, IndexedDB, and FileSystem, you can access the table location, orientation, switch, and Table value of the Gas Monitoring System by Using CURD.

Http://www.hightopo.com/guide/guide/core/serialization/examples/example_exportimport.html

HTML5 storage also provides a Web SQL Database method. Although it is supported by browsers and is the only storage of relational Database structures, W3C and its maintenance and development are stopped, so we will not introduce it here: Beware. this specification is no longer in active maintenance and the Web Applications Working Group does not intend to maintain it further.

The entire example is to serialize and deserialize the DataModel Data Model Information of HT for Web. This process is very simple through dataModel. serialize () serializes the model into a JSON string and uses dataModel. deserialize (jsonString) deserializes the JSON string memory to produce model information, and the storage is mainly to operate on JSON strings.

First, we will introduce the simplest Storage method LocalStorage. The Code is as follows. There is almost no need to introduce the simple Key-Value Pair Storage structure of Key-Value. In addition to the persistent Storage of localStorage, Web Storage, also for the session of the sessionStorage method, generally localStorage is more commonly used, more can refer to the http://www.w3.org/TR/webstorage/

Functionsave (dataModel) {varvalue = dataModel. serialize (); window. localStorage ['datamodel '] = value; window. localStorage ['datacount'] = dataModel. size (); console. log (dataModel. size () + 'datasaresaved'); returnvalue;} functionrestore (dataModel) {varvalue = window. localStorage ['datamodel ']; if (value) {DataModel. deserialize (value); console. log (window. localStorage ['datacount'] + 'datasarerestored'); returnvalue;} return '';} functionclear () {if (window. localStorage ['datamodel ']) {console. log (window. localStorage ['datacount'] + 'datasarecleared'); deletewindow. localStorage ['datamodel ']; deletewindow. localStorage ['datacount'];}


The oldest storage method is Cookie. In this example, I can only store the information of one metadata. This storage method has limited content and is only suitable for simple information storage, the access interface is designed to be extremely anti-human. To introduce the integrity of the HTML5 storage solution, I listed it by the way:

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 () + 'datasaresaved'); returnvalue;} functionrestore (dataModel) {varvalue = getCookieValue ('datamodel '); if (value) {DataModel. deserialize (value); console. log (getCookieValue ('datacount') + 'datasarerestored'); returnvalue;} return '';} functionclear () {if (getCookieValue ('datamodel ') {console. log (getCookieValue ('datacount') + 'datasarecleared'); document. cookie = "DataModel =; expires = Thu, 01Jan197000: 00: 00UTC"; document. cookie = "DataCount =; expires = Thu, 01Jan197000: 00: 00UTC ";}}


Currently, the more practical and powerful storage method is the Indexed Database API. IndexedDB can store structured objects and search by indexing keys and indexes. Currently, various browsers have gradually supported the storage method of IndexedDB, the Code is as follows. Pay attention to the fact that many IndexedDB operation interfaces are similar to the asynchronous callback method of NodeJS. In particular, the connection to the cursor continue during query is the method of asynchronous callback of the onsuccess function, therefore, it is easier to use the same code as 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 () + 'datasaresaved') ;}; 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 () + 'datasarerestored') ;}}; return '';} functionclear () {vartx = db. transaction ("meters", "readwrite"); varstore = tx. objectStore ("meters" cannot get. result; if (res) {store. delete (res. value. id); res. continue (); count ++;} else {console. log (count + 'datasarecleared ');}};}


Finally, the FileSystem API is equivalent to the storage method used to operate on local files. Currently, few browsers are supported, and its interface standards are also being developed and changed, for example, when I write this code, most of the webkitStorageInfo used in the literature has been navigator. webkitPersistentStorage and navigator. webkitTemporaryStorage is used as an alternative. The stored files can be stored through filesystem: Metadata The wonderful application of qigu blame.

Navigator. webkitPersistentStorage. queryUsageAndQuota (function (usage, quota) {console. log ('Persistent: '+ usage +'/'+ quota +'-'+ usage/quota +' % ');}); navigator. webkitPersistentStorage. requestQuota (2*1024*1024 comment ', {create: true}, function (fileEntry) {console. log (fileEntry. toURL (); fileEntry. createWriter (function (fileWriter) {fileWriter. onwriteend = function () {console. log (dataModel. size () + 'datasaresaved') ;}; varblob = newBlob ([value], {type: 'text/upload', {create: false}, function (fileEntry) {fileEntry. remove (function () {console. log (fileEntry. toURL () + 'isremoved ');});});}


Browser-Side storage is still in rapid development. In fact, in addition to the above several types of applications Cache, I believe there will be new talent in the future, although "Cloud" is a general trend, however, the client does not have to go through the extreme "thin" solution. So many client storage methods have emerged over the years, which indicates that the market demand for more powerful clients is strong, of course, the client programmers are at the turbulent stage. In addition to adapting to Mouse and Touch, they also need to adapt to various screens. Now they have to consider adapting to various types of storage, hope this article can be in the selection of client storage solution a little help, the last section based on HT for Web operation HTML5 storage example Video Effect: http://v.youku.com/v_show/id_XODUzODU2MTY0.html

Http://www.hightopo.com/guide/guide/core/serialization/examples/example_exportimport.html


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.