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

作者: 前端知识  发布:2019-06-24

关于我:njuyz

图片 1

(乐乎果壳网:@njuyz) 个人主页 · 笔者的稿子 · 11

图片 2

AppCache

只要您的Web应用中有一点作用(也许全体应用)须要在脱离服务器的气象下采用,那么就能够通过AppCache来令你的用户在离线状态下也能选拔。你所急需做的正是创办壹个陈设文件,在在那之中内定哪些财富须求被缓存,哪些无需。其余,还是可以够在其间钦点有个别联机能源在脱机条件下的代替财富。

AppCache的陈设文件一般是二个以.appcache最终的公文文件(推荐写法)。文件以CACHE MANIFEST千帆竞发,包蕴下列三部分内容:

  • CACHE – 钦命了怎么财富在用户率先次访问站点的时候须求被下载并缓存
  • NETWORK – 钦命了如何能源须要在同步条件下手艺访问,那个能源从不被缓存
  • FALLBACK – 钦定了上述财富在脱机条件下的代替能源

示例

笔者们不妨来探视在此以前的例子。在联系人和评价的局地,大家得以每日保存用户输入的事物。那样一来,即便用户相当的大心关闭了浏览器,在此之前输入的东西也不会丢掉。对于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);
   }
});

示例

首先,你必要在页面上钦定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奥迪Q3K部分选用通配符把装有不该被缓存的财富写出来。

你无需显式地缓存包蕴配置文件的页面,因为那么些页面会自动被缓存。接下来大家为挂钩和探讨的页面定义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:
...

IndexedDB

在作者个人看来,这是最有意思的一种才干。它能够保留多量因此索引(indexed)的多寡在浏览器端。那样一来,就能够在客户端保存复杂对象,大文书档案等等数据。而且用户可以在离线情状下访问它们。这一风味大概适用于具备品类的Web应用:即使您写的是邮件客户端,你可以缓存用户的邮件,以供稍后再看;假设您写的是相册类应用,你能够离线保存用户的肖像;要是你写的是GPS导航,你能够缓存用户的门道……不知凡几。

IndexedDB是二个面向对象的数据库。那就象征在IndexedDB中既不存在表的定义,也未曾SQL,数据是以键值对的花样保留的。当中的键不仅可以够是字符串和数字等基础项目,也得以是日期和数组等繁杂类型。那个数据库自身构建于积存(store,二个store类似于关系型数据中表的定义)的基础上。数据库中各类值都不可能不要有对应的键。每一个键不仅可以够自动生成,也能够在插入值的时候钦定,也能够取自于值中的有些字段。要是你调整动用值中的字段,那么只可以向里面增添Javascript对象,因为基础数据类型不像Javascript对象那样有自定义属性。

Web应用中的离线数据存储

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

本文由 伯乐在线 - njuyz 翻译。未经许可,禁止转发!
英文出处:Nettuts 。迎接插足翻译组。

为了提高Web应用的用户体验,想必许多开垦者都会项目中引进离线数据存储机制。但是面前蒙受琳琅满指标离线数据技巧,哪一类才是最能满足项目必要的啊?本文将帮助各位找到最合适的那个。

LocalStorage和SessionStorage

若是您想在Javascript代码里面保存些数据,那么那八个东西就派上用场了。前一个足以保存数据,永远不会晚点(expire)。只借使平等的域和端口,全部的页面中都能访问到通过LocalStorage保存的数额。举个简单的事例,你能够用它来保存用户安装,用户可以把他的民用爱好保存在当下利用的微机上,现在打开应用的时候能够平素加载。后者也能保留数据,然而只要关闭浏览器窗口(译者注:浏览器窗口,window,要是是多tab浏览器,则此处指代tab)就失效了。而且那几个多少不能在不一致的浏览器窗口之间共享,尽管是在不一样的窗口中做客同三个Web应用的其余页面。

旁注:有一点点亟需提示的是,LocalStorage和SessionStorage里面只好保留基本项指标数量,也便是字符串和数字类型。其它具备的数目可以经过独家的toString()方法转化后保存。借令你想保留多个对象,则要求利用JSON.stringfy方法。(假诺这么些指标是多少个类,你能够复写它暗中同意的toString()方法,这些方法会自动被调用)。

引言

随着HTML5的赶到,各个Web离线数据技巧进入了开荒职员的视线。诸如AppCache、localStorage、sessionStorage和IndexedDB等等,每一类技艺都有它们分别适用的范围。举例AppCache就比较相符用来离线起动应用,大概在离线状态下使应用的一片段功能照常运作。接下来笔者将会为大家作详细介绍,并且用有个别代码片段来展现怎么着运用这几个手艺。

总结

能够望见,在Web应用中央银行使离线数据并不是十一分复杂。希望因而翻阅那篇小说,各位能够在Web应用中进入离线数据的功力,使得你们的接纳更加的温馨易用。你能够在这里下载全部的源码,尝试一下,可能涂改,也许用在你们的施用中。

赞 收藏 评论

示例

在这些例子中,我们用二个音乐特辑应用作为示范。但是自个儿并不筹划在此地原原本本体现整个应用,而是把关系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应用中的离线数据存款和储蓄

关键词: 金沙澳门官网

上一篇:框架比较,十款最棒的JavaScript开采框架
下一篇:没有了