gears旅程
gears是google推出的新一代web技术,用于离线应用,本地存储,提升js性能等,使用时网页会要求安装一个东西,就像flash要安装一个player,silverlight要安装一个runtime一样,地址为:http://gears.google.com/
Gears 模块包括:
LocalServer 在本地缓存和提供应用程序资源(HTML、JavaScript、图片等) | |
Database 将数据存储在本地可完全搜索的关系数据库中 | |
WorkerPool 通过异步执行资源密集型的操作使网络应用程序的响应速度更快 |
附一个官网的demo:http://code.google.com/intl/zh-CN/apis/gears/samples/hello_world_database.html
gears的本地存储原理比较简单,通过一个sqlite数据库将数据保存在本地,通过js进行数据库操纵。
gears的数据在各个浏览器中是不互通的,chrome中存储的数据只能在chrome中被读取。
通过一段js去调用gears:
<script src="gears_init.js"></script> <script> if (!window.google || !google.gears) { location.href = "http://gears.google.com/?action=install&message=<your welcome message>" + "&return=<your website url>"; } </script>
gears_init.js的路径为:http://code.google.com/intl/zh-CN/apis/gears/gears_init.js
看了源码之后觉得初始化工作还是比较简单的:
(function() { // We are already defined. Hooray! if (window.google && google.gears) { return; } var factory = null; // Firefox if (typeof GearsFactory != 'undefined') { factory = new GearsFactory(); } else { // IE try { factory = new ActiveXObject('Gears.Factory'); // privateSetGlobalObject is only required and supported on IE Mobile on // WinCE. if (factory.getBuildInfo().indexOf('ie_mobile') != -1) { factory.privateSetGlobalObject(this); } } catch (e) { // Safari if ((typeof navigator.mimeTypes != 'undefined') && navigator.mimeTypes["application/x-googlegears"]) { factory = document.createElement("object"); factory.style.display = "none"; factory.width = 0; factory.height = 0; factory.type = "application/x-googlegears"; document.documentElement.appendChild(factory); if(factory && (typeof factory.create == 'undefined')) { // If NP_Initialize() returns an error, factory will still be created. // We need to make sure this case doesn't cause Gears to appear to // have been initialized. factory = null; } } } } // *Do not* define any objects if Gears is not installed. This mimics the // behavior of Gears defining the objects in the future. if (!factory) { return; } // Now set up the objects, being careful not to overwrite anything. // // Note: In Internet Explorer for Windows Mobile, you can't add properties to // the window object. However, global objects are automatically added as // properties of the window object in all browsers. if (!window.google) { google = {}; } if (!google.gears) { google.gears = {factory: factory}; } })();
核心代码就这些,ie是通过ActiveXObject实现的。
而具体的操纵数据库的代码:
var recentPhrases = ['', '', '']; // Get the 3 most recent entries. Delete any others. var rs = db.execute('select * from Demo order by Timestamp desc'); var index = 0; while (rs.isValidRow()) { if (index < 3) { recentPhrases[index] = rs.field(0); } else { db.execute('delete from Demo where Timestamp=?', [rs.field(1)]); } ++index; rs.next(); } rs.close();
读取后将数据写入dom元素,这即是本地存储的应用。
此外,gears还有其他一系列api,例如地理定位,离线应用等,更多的例子,在http://code.google.com/intl/zh-CN/apis/gears/sample.html