>

Web应用中的离线数据存款和储蓄

- 编辑:至尊游戏网站 -

Web应用中的离线数据存款和储蓄

Web应用中的离线数据存款和储蓄

2014/02/15 · HTML5, JavaScript · HTML5, Javascript

本文由 伯乐在线 - njuyz 翻译。未经许可,幸免转发!
匈牙利(Magyarország)语出处:Nettuts+。迎接参加翻译组。

为了升高Web应用的客商体验,想必非常多开拓者都会项目中引进离线数据存款和储蓄机制。可是面临形形色色的离线数据工夫,哪豆蔻年华种才是最能满意项目供给的吗?本文将扶助各位找到最合适的那八个。

引言

乘势HTML5的赶来,各类Web离线数据技巧进入了开拓人士的视线。诸如AppCache、localStorage、sessionStorage和IndexedDB等等,每风姿罗曼蒂克种技艺都有它们分别适用的规模。举个例子AppCache就比较相符用来离线起动应用,或许在离线状态下使应用的意气风发局地功能照常运作。接下来笔者将会为大家作详细介绍,何况用部分代码片段来展示怎么着利用这一个才干。

AppCache

假诺你的Web应用中有一点效应(只怕全部应用)须求在退出服务器的意况下使用,那么就足以经过AppCache来让您的顾客在离线状态下也能运用。你所急需做的正是创办三个布局文件,在内部钦赐哪些能源须要被缓存,哪些无需。此外,还能在此中内定有些联机财富在脱机条件下的代表能源。

AppCache的安顿文件日常是一个以.appcache末了的文书文件(推荐写法)。文件以CACHE MANIFEST初步,包蕴下列三有个别剧情:

  • CACHE – 内定了怎么着资源在客商率先次访问站点的时候要求被下载并缓存
  • NETWORK – 内定了如何财富需求在一起条件下本领访谈,这么些财富从不被缓存
  • FALLBACK – 钦点了上述财富在脱机条件下的代表能源

示例

先是,你必要在页面上内定AppCache的布置文件:

XHTML

<!DOCTYPE html> <html manifest="manifest.appcache"> ... </html>

1
2
3
4
<!DOCTYPE html>
<html manifest="manifest.appcache">
...
</html>

在那处相对记得在劳动器端发表上述配置文件的时候,须求将MIME类型设置为text/cache-manifest,不然浏览器不可能平常解析。

接下去是创造早先定义好的各类能源。大家只要在此个示例中,你付出的是贰个互动类站点,客商可以在上头联系别人而且发布商酌。客商在离线的状态下依然得以访问网址的静态部分,而沟通以致公布商量的页面则会被别的页面替代,不可能访问。

好的,大家那就动手定义这个静态能源:

JavaScript

CACHE MANIFEST CACHE: /about.html /portfolio.html /portfolio_gallery/image_1.jpg /portfolio_gallery/image_2.jpg /info.html /style.css /main.js /jquery.min.js

1
2
3
4
5
6
7
8
9
10
11
CACHE MANIFEST
 
CACHE:
/about.html
/portfolio.html
/portfolio_gallery/image_1.jpg
/portfolio_gallery/image_2.jpg
/info.html
/style.css
/main.js
/jquery.min.js

旁注:配置文件写起来有一点非常不平价。比方来讲,纵然您想缓存整个目录,你不能直接在CACHE部分选拔通配符(*),而是只可以在NETWO奥迪Q5K部分采取通配符把具备不应该被缓存的财富写出来。

您无需显式地缓存富含配置文件的页面,因为这些页面会自动被缓存。接下来大家为挂钩和评价的页面定义FALLBACK部分:

JavaScript

FALLBACK: /contact.html /offline.html /comments.html /offline.html

1
2
3
FALLBACK:
/contact.html /offline.html
/comments.html /offline.html

终极我们用贰个通配符来阻止别的的财富被缓存:

JavaScript

NETWORK: *

1
2
NETWORK:
*

最终的结果正是底下那样:

JavaScript

CACHE MANIFEST CACHE: /about.html /portfolio.html /portfolio_gallery/image_1.jpg /portfolio_gallery/image_2.jpg /info.html /style.css /main.js /jquery.min.js FALLBACK: /contact.html /offline.html /comments.html /offline.html NETWORK: *

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
CACHE MANIFEST
 
CACHE:
/about.html
/portfolio.html
/portfolio_gallery/image_1.jpg
/portfolio_gallery/image_2.jpg
/info.html
/style.css
/main.js
/jquery.min.js
 
FALLBACK:
/contact.html /offline.html
/comments.html /offline.html
 
NETWORK:
*

还恐怕有后生可畏件很要紧的思想政治工作要记得:你的财富只会被缓存贰遍!也正是说,如若财富革新了,它们不会自动更新,除非你改改了陈设文件。所以有二个最棒执行是,在布署文件中增添方兴未艾项版本号,每趟换代财富的时候顺便更新版本号:

JavaScript

CACHE MANIFEST # version 1 CACHE: ...

1
2
3
4
5
6
CACHE MANIFEST
 
# version 1
 
CACHE:
...

LocalStorage和SessionStorage

即便您想在Javascript代码里面保存些数据,那么那多个东西就派上用场了。前二个足以保留数据,长久不会晚点(expire)。只假使相同的域和端口,全数的页面中都能访问到通过LocalStorage保存的数码。举个简单的例证,你能够用它来保存客商设置,客商能够把她的民用喜好保存在目前采纳的管理器上,现在展开应用的时候能够直接加载。前面一个也能保存数据,然则假如关闭浏览器窗口(译者注:浏览器窗口,window,借使是多tab浏览器,则此处指代tab)就失效了。並且那几个多少不可能在不一致的浏览器窗口之间分享,就算是在差别的窗口中做客同一个Web应用的别的页面。

旁注:有几许亟需提示的是,LocalStorage和SessionStorage里面只好保留基本项目标数码,也等于字符串和数字类型。其余具备的多少可以经过各自的toString()方法转变后保存。要是您想保留一个对象,则须求采用JSON.stringfy方法。(假如这些目的是三个类,你能够复写它暗中同意的toString()方法,那些方法会自动被调用)。

示例

大家不要紧来拜谒后边的事例。在联系人和切磋的有的,大家得以每一日保存客户输入的事物。那样一来,就算客户非常大心关闭了浏览器,以前输入的事物也不会扬弃。对于jQuery来说,这些功用是小菜大器晚成碟。(注意:表单中各样输入字段都有id,在那地大家就用id来替代具体的字段)

JavaScript

$('#comments-input, .contact-field').on('keyup', function () { // let's check if localStorage is supported if (window.localStorage) { localStorage.setItem($(this).attr('id'), $(this).val()); } });

1
2
3
4
5
6
$('#comments-input, .contact-field').on('keyup', function () {
   // let's check if localStorage is supported
   if (window.localStorage) {
      localStorage.setItem($(this).attr('id'), $(this).val());
   }
});

历次提交联系人和争辨的表单,大家必要清空缓存的值,大家能够那样管理提交(submit)事件:

JavaScript

$('#comments-form, #contact-form').on('submit', function () { // get all of the fields we saved $('#comments-input, .contact-field').each(function () { // get field's id and remove it from local storage localStorage.removeItem($(this).attr('id')); }); });

1
2
3
4
5
6
7
$('#comments-form, #contact-form').on('submit', function () {
   // get all of the fields we saved
   $('#comments-input, .contact-field').each(function () {
      // get field's id and remove it from local storage
      localStorage.removeItem($(this).attr('id'));
   });
});

最后,每一次加载页面包车型客车时候,把缓存的值填充到表单上就能够:

JavaScript

// get all of the fields we saved $('#comments-input, .contact-field').each(function () { // get field's id and get it's value from local storage var val = localStorage.getItem($(this).attr('id')); // if the value exists, set it if (val) { $(this).val(val); } });

1
2
3
4
5
6
7
8
9
// get all of the fields we saved
$('#comments-input, .contact-field').each(function () {
   // get field's id and get it's value from local storage
   var val = localStorage.getItem($(this).attr('id'));
   // if the value exists, set it
   if (val) {
      $(this).val(val);
   }
});

IndexedDB

在小编个人看来,那是最风趣的意气风发种本领。它能够保存一大波经过索引(indexed)的多少在浏览器端。那样一来,就能够在客商端保存复杂对象,大文书档案等等数据。何况客商能够在离线情形下访问它们。那意气风发风味大约适用于具有品类的Web应用:倘让你写的是邮件客商端,你能够缓存顾客的邮件,以供稍后再看;假使你写的是相册类应用,你能够离线保存客商的照片;假使您写的是GPS导航,你能够缓存顾客的不二秘籍……不计其数。

IndexedDB是贰个面向对象的数据库。那就象征在IndexedDB中既海市蜃楼表的概念,也未曾SQL,数据是以键值对的款式保留的。在那之中的键不仅可以够是字符串和数字等基础项目,也能够是日期和数组等繁琐类型。那么些数据库本人构建于积攒(store,一个store类似于关系型数据中表的定义)的根底上。数据库中每种值都必须求有照望的键。各个键不只能够自动生成,也足以在插入值的时候钦定,也能够取自于值中的有些字段。假诺您调节利用值中的字段,那么只可以向当中加多Javascript对象,因为基础数据类型不像Javascript对象那样有自定义属性。

示例

在这里个例子中,我们用三个音乐专辑应用作为示范。可是本人并不许备在这里处自始至终显示整个应用,而是把事关IndexedDB的部分挑出来解释。若是我们对那个Web应用感兴趣的话,小说的背后也提供了源代码的下载。首先,让咱们来展开数据库并创制store:

JavaScript

// check if the indexedDB is supported if (!window.indexedDB) { throw 'IndexedDB is not supported!'; // of course replace that with some user-friendly notification } // variable which will hold the database connection var db; // open the database // first argument is database's name, second is it's version (I will talk about versions in a while) var request = indexedDB.open('album', 1); request.onerror = function (e) { console.log(e); }; // this will fire when the version of the database changes request.onupgradeneeded = function (e) { // e.target.result holds the connection to database db = e.target.result; // create a store to hold the data // first argument is the store's name, second is for options // here we specify the field that will serve as the key and also enable the automatic generation of keys with autoIncrement var objectStore = db.createObjectStore('cds', { keyPath: 'id', autoIncrement: true }); // create an index to search cds by title // first argument is the index's name, second is the field in the value // in the last argument we specify other options, here we only state that the index is unique, because there can be only one album with specific title objectStore.createIndex('title', 'title', { unique: true }); // create an index to search cds by band // this one is not unique, since one band can have several albums objectStore.createIndex('band', 'band', { unique: false }); };

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// check if the indexedDB is supported
if (!window.indexedDB) {
    throw 'IndexedDB is not supported!'; // of course replace that with some user-friendly notification
}
 
// variable which will hold the database connection
var db;
 
// open the database
// first argument is database's name, second is it's version (I will talk about versions in a while)
var request = indexedDB.open('album', 1);
 
request.onerror = function (e) {
    console.log(e);
};
 
// this will fire when the version of the database changes
request.onupgradeneeded = function (e) {
    // e.target.result holds the connection to database
    db = e.target.result;
 
    // create a store to hold the data
    // first argument is the store's name, second is for options
    // here we specify the field that will serve as the key and also enable the automatic generation of keys with autoIncrement
    var objectStore = db.createObjectStore('cds', { keyPath: 'id', autoIncrement: true });
 
    // create an index to search cds by title
    // first argument is the index's name, second is the field in the value
    // in the last argument we specify other options, here we only state that the index is unique, because there can be only one album with specific title
    objectStore.createIndex('title', 'title', { unique: true });
 
    // create an index to search cds by band
    // this one is not unique, since one band can have several albums
    objectStore.createIndex('band', 'band', { unique: false });
};

信赖上边的代码依旧卓殊老妪能解的。猜度您也只顾到上述代码中开发数据库时会传入一个版本号,还用到了onupgradeneeded事件。当你以较新的本子打开数据库时就能触发那么些事件。借使相应版本的数据库尚荒诞不经,则会触发事件,随后我们就能够创建所需的store。接下来我们还成立了八个目录,八个用于标题搜索,一个用来乐队寻找。现在让大家再来看看如何增删专辑:

JavaScript

// adding $('#add-album').on('click', function () { // create the transaction // first argument is a list of stores that will be used, second specifies the flag // since we want to add something we need write access, so we use readwrite flag var transaction = db.transaction([ 'cds' ], 'readwrite'); transaction.onerror = function (e) { console.log(e); }; var value = { ... }; // read from DOM // add the album to the store var request = transaction.objectStore('cds').add(value); request.onsuccess = function (e) { // add the album to the UI, e.target.result is a key of the item that was added }; }); // removing $('.remove-album').on('click', function () { var transaction = db.transaction([ 'cds' ], 'readwrite'); var request = transaction.objectStore('cds').delete(/* some id got from DOM, converted to integer */); request.onsuccess = function () { // remove the album from UI } });

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// adding
$('#add-album').on('click', function () {
    // create the transaction
    // first argument is a list of stores that will be used, second specifies the flag
    // since we want to add something we need write access, so we use readwrite flag
    var transaction = db.transaction([ 'cds' ], 'readwrite');
    transaction.onerror = function (e) {
        console.log(e);
    };
    var value = { ... }; // read from DOM
    // add the album to the store
    var request = transaction.objectStore('cds').add(value);
    request.onsuccess = function (e) {
        // add the album to the UI, e.target.result is a key of the item that was added
    };
});
 
// removing
$('.remove-album').on('click', function () {
    var transaction = db.transaction([ 'cds' ], 'readwrite');
    var request = transaction.objectStore('cds').delete(/* some id got from DOM, converted to integer */);
    request.onsuccess = function () {
        // remove the album from UI
    }
});

是还是不是看起来直接明了?这里对数据库全数的操作都依照事务的,只有如此能力保障数据的意气风发致性。现在最后要做的就是展现音乐特辑:

JavaScript

request.onsuccess = function (e) { if (!db) db = e.target.result; var transaction = db.transaction([ 'cds' ]); // no flag since we are only reading var store = transaction.objectStore('cds'); // open a cursor, which will get all the items from database store.openCursor().onsuccess = function (e) { var cursor = e.target.result; if (cursor) { var value = cursor.value; $('#albums-list tbody').append(' '+ value.title +''+ value.band +''+ value.genre +''+ value.year +'

1
2
3
4
5
6
7
8
9
10
11
12
request.onsuccess = function (e) {
    if (!db) db = e.target.result;
 
    var transaction = db.transaction([ 'cds' ]); // no flag since we are only reading
    var store = transaction.objectStore('cds');
    // open a cursor, which will get all the items from database
    store.openCursor().onsuccess = function (e) {
        var cursor = e.target.result;
        if (cursor) {
            var value = cursor.value;
            $('#albums-list tbody').append('
'+ value.title +''+ value.band +''+ value.genre +''+ value.year +'

‘); // move to the next item in the cursor cursor.continue(); } }; }

那亦不是十二分复杂。能够瞥见,通过运用IndexedDB,能够很自在的保留复杂对象,也能够透过索引来查找想要的剧情:

JavaScript

function getAlbumByBand(band) { var transaction = db.transaction([ 'cds' ]); var store = transaction.objectStore('cds'); var index = store.index('band'); // open a cursor to get only albums with specified band // notice the argument passed to openCursor() index.openCursor(IDBKeyRange.only(band)).onsuccess = function (e) { var cursor = e.target.result; if (cursor) { // render the album // move to the next item in the cursor cursor.continue(); } }); }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getAlbumByBand(band) {
    var transaction = db.transaction([ 'cds' ]);
    var store = transaction.objectStore('cds');
    var index = store.index('band');
    // open a cursor to get only albums with specified band
    // notice the argument passed to openCursor()
    index.openCursor(IDBKeyRange.only(band)).onsuccess = function (e) {
        var cursor = e.target.result;
        if (cursor) {
            // render the album
            // move to the next item in the cursor
            cursor.continue();
        }
    });
}

应用索引的时候和应用store如出活龙活现辙,也能通过游标(cursor)来遍历。由于同一个索引值名下也许有点条数据(假设索引不是unique的话),所以那边大家供给接纳IDBKeyRange。它能依靠钦定的函数对结果集举行过滤。这里,大家只想依靠钦定的乐队实行查找,所以我们用到了only()函数。也能选取此外类似于lowerBound()upperBound()bound()等函数,它们的效益也是不问可知的。

总结

能够瞥见,在Web应用中使用离线数据并非十分复杂。希望经过翻阅那篇文章,各位能够在Web应用中进入离线数据的作用,使得你们的采取更加的融洽易用。你能够在这里下载全数的源码,尝试一下,或许修改,恐怕用在你们的应用中。

赞 收藏 评论

至于小编:njuyz

图片 1

(乐乎天涯论坛:@njuyz) 个人主页 · 作者的稿子 · 11

图片 2

本文由门户名站发布,转载请注明来源:Web应用中的离线数据存款和储蓄