5 offline storage methods for HTML5 Web 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.
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/
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 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:
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"; }}
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; 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'); }; 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); 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; 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 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, 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 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