localforage--easy to implement WEB offline storage

Source: Internet
Author: User

Web applications have offline functionality, such as saving large numbers of datasets and binaries. You can even do things like cache MP3 files. Browser technology can save offline data and a lot of storage. But the problem is, how to choose the appropriate technology, how to facilitate the flexible implementation.

If you need to develop a Web application that supports offline storage and doesn't know where to start, then this article is exactly what you need.

Localstorage allows you to implement basic data storage, but it is slow and cannot handle binary data. IndexedDB and Websql are asynchronous, fast, and support big data sets, but their APIs are a bit more complex to use. Not only that, IndexedDB and Websql are not supported by all the mainstream browser vendors, and this situation is unlikely to change recently.

Mozilla has developed a library called Localforage, which makes it an easy task to store offline data in any browser.

Localforage is a very simple JavaScript library that provides APIs such as get,set,remove,clear and length, and has the following features:

    • Asynchronous APIs that support callbacks;
    • Supports Indexeddb,websql and localstorage three storage modes (automatically loading the best drivers for you);
    • Supports BLOBs and any type of data, allowing you to store pictures, files, and more.
    • Support ES6 Promises;

Support for IndexedDB and Websql allows you to store more data for your Web application than the Localstorage allows. The non-blocking nature of its APIs makes your application faster and does not suspend the main thread because of Get/set calls.

Localstorage

Traditional API in many ways is actually very good, simple to use, no complex data structure. If you have a configuration message in your application that needs to be kept, you can write:

1234567891011 // 需要离线保存的配置数据var config = {    fullName: document.getElementById(‘name‘).getAttribute(‘value‘),    userId: document.getElementById(‘id‘).getAttribute(‘value‘)}; // 保存起来,供下次使用localStorage.setItem(‘config‘, JSON.stringify(config)); // 从离线存储中读取出来var config = JSON.parse(localStorage.getItem(‘config‘));

Note that data stored using localstorage needs to be saved as strings, so we need JSON serialization and deserialization when saving and reading.

It looks as though it is easy to use, but you will soon find several problems with Localstorage:

    1. it is synchronous. no matter how big the data is, we need to wait for the data to be read and parsed from disk, which slows down our application's responsiveness. This is especially bad on mobile devices, where the main thread is suspended until the data is taken out, making your application look slow and even unresponsive.

    2. it only supports strings. serial numbers and deserialization are required using Json.parse and json.stringify. This is because only JavaScript string values are supported in Localstorage. Numeric, Boolean, Blob-type data is not supported.

Localforage

Localforage can solve the above problem, let's compare the difference between IndexedDB and localforage storing the same data:

IndexedDB Code:
12345678910111213141516171819202122232425262728293031323334 // IndexedDB.var db;var dbName = "dataspace";var users = [ {id: 1, fullName: ‘Matt‘}, {id: 2, fullName: ‘Bob‘} ];var request = indexedDB.open(dbName, 2);request.onerror = function(event) {    // 错误处理};request.onupgradeneeded = function(event) {    db = event.target.result;    var objectStore = db.createObjectStore("users", { keyPath: "id" });    objectStore.createIndex("fullName", "fullName", { unique: false });    objectStore.transaction.oncomplete = function(event) {        var userObjectStore = db.transaction("users", "readwrite").objectStore("users");    }}; var transaction = db.transaction(["users"], "readwrite");// 所有数据都添加到数据后调用transaction.oncomplete = function(event) {    console.log("All done!");};transaction.onerror = function(event) {    // 错误处理}; var objectStore = transaction.objectStore("users");for (var i in users) {    var request = objectStore.add(users[i]);    request.onsuccess = function(event) {        // 里面包含我们需要的用户信息        console.log(event.target.result);    };}

Using the Websql implementation may not be that lengthy, but it's also a bit complicated. Using Localforage, you can write this:

Localforage Code:
12345 // 保存用户信息varusers = [ {id: 1, fullName: ‘Matt‘}, {id: 2, fullName: ‘Bob‘} ];localForage.setItem(‘users‘, users, function(result) {    console.log(result);});

Isn't it a lot simpler?

Support for non-string data

For example, you want to download a user's profile picture and cache it for offline use. It is easy to save binary data using Localforage:

123456789101112131415161718 // 使用 AJAX 下载图片var request = new XMLHttpRequest(); // 以获取第一个用户的资料图片为例request.open(‘GET‘, "/users/1/profile_picture.jpg", true);request.responseType = ‘arraybuffer‘; // 当 AJAX 调用完成,把图片保存到本地request.addEventListener(‘readystatechange‘, function() {    if (request.readyState === 4) { // readyState DONE        // 保存的是二进制数据,如果用 localStorage 就无法实现        localForage.setItem(‘user_1_photo‘, request.response, function() {            // 图片已保存,想怎么用都可以        });    }}); request.send()

Next time, you can read the photo from the cache with just three lines of code:

1234 localForage.getItem(‘user_1_photo‘, function(photo) {    // 获取到图片数据后,可以通过创建 data URI 或者其它方法来显示    console.log(photo);});
Callbacks & Promises

If you do not like to use callbacks in your code, you can use ES6 Promisesto replace the localforage callback parameters. Let's use the above photo example to see the code using Promises:

1234 localForage.getItem(‘user_1_photo‘).then(function(photo) {    // 获取到图片数据后,可以通过创建 data URI 或者其它方法来显示    console.log(photo);});
Cross-browser support

Localforage supports all modern browsers (including IE8 and later versions). The following browsers and platforms are supported:

    • Android Browser 2.1
    • Blackberry 7
    • Chrome 23   (Chrome 4.0 with localstorage)
    • Chrome for Android +
    • Firefox 10   (Firefox 3.5 with localstorage)
    • Firefox for Android +
    • Firefox OS 1.0
    • ie ten   (ie 8 with localstorage)
    • ie Mobile 10
    • Opera   (opera 10.5 with Localstorage)
    • opera Mobile one /li>
    • phonegap/apache Cordova 1.2.0
    • Safari 3.1   (includes Mobile Safari)
    • reprint: http://www.cnblogs.com/lhb25/p/localforage-offline-storage-improved.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.