LocalForage -- easily implement offline Web Storage

Source: Internet
Author: User

Web applications have offline functions, such as saving a large number of datasets and binary files. You can even cache MP3 files. Browser technology can save offline data and store a large amount of data. But the question is how to choose the right technology and how to implement it conveniently and flexibly.

If you need to developWebThe application does not know where to start, so this article is exactly what you need.

Articles you may be interested in
  • Nine incredible WebGL application trials
  • Let you forget the 15 HTML5 games of Flash
  • 10 popular jQuery plug-ins worth your favorites
  • My friends are stunned! 8 superb Web effects
  • Web Front-end developers must read excellent article recommendations

 

LocalStorage allows you to implement basic data storage, but it is slow and cannot process binary data. IndexedDB and WebSQL are asynchronous and fast. They support large datasets, but their API usage is a bit complicated. In addition, IndexedDB and WebSQL are not supported by all mainstream browser vendors. This situation is unlikely to change recently.

Mozilla developed a library named localForage, which makes it easy to store offline data in any browser.

LocalForage is very easy to use.JavaScriptLibrary, provides get, set, remove, clear and length APIs, and has the following features:

  • Asynchronous APIs supporting callback;
  • Supports three storage modes: IndexedDB, WebSQL, and localStorage (the best driver is automatically loaded for you );
  • Supports BLOB and any type of data, allowing you to store images, files, and so on.
  • ES6 Promises is supported;

The support for IndexedDB and WebSQL allows youWebApplications store more data than localStorage allows. The non-blocking nature of its API makes your application faster and does not suspend the main thread because of Get/Set calls.

LocalStorage

Traditional APIs are actually very good in many aspects. They are easy to use and do not have complex data structures. If you have a configuration information to maintain in your application, you can write as follows:

// Configure var config = {fullName: document. getElementById ('name '). getAttribute ('value'), userId: document. getElementById ('id '). getAttribute ('value')}; // save it for the next use of localStorage. setItem ('config', JSON. stringify (config); // read var config = JSON from offline storage. parse (localStorage. getItem ('config '));

Note that data stored using localStorage must be saved as strings. Therefore, JSON serialization and deserialization are required during storage and reading.

It seems to be easy to use, but you will soon find several problems with localStorage:

LocalForage

LocalForage can solve the above problem. Next we will compare the differences between the same data stored in IndexedDB and localForage:

IndexedDB code:
// 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) {// error handling}; request. onupgradeneeded = function (event) {db = event.tar get. 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"); // call transaction after all data is added to the data. oncomplete = function (event) {console. log ("All done! ") ;}; Transaction. onerror = function (event) {// error handling}; var objectStore = transaction. objectStore ("users"); for (var I in users) {var request = objectStore. add (users [I]); request. onsuccess = function (event) {// contains the required user information lele.log(event.tar get. result );};}

WebSQL implementation may not be too lengthy, but it is also a bit complicated. Use localForage to write:

LocalForage code:
// Save the user information var users = [{id: 1, fullName: 'Matt '}, {id: 2, fullName: 'bob'}]; localForage. setItem ('users', users, function (result) {console. log (result );});

Is it much simpler?

Data that is not a string is supported

For example, you want to download a user's profile image and cache it for offline use. Using localForage can easily save binary data:

// Use AJAX to download the image var request = new XMLHttpRequest (); // take the first user's profile image as an example request. open ('get', "/users/1/profile_picture.jpg", true); request. responseType = 'arraybuffer'; // when the AJAX call is complete, save the image to the local request. addEventListener ('readystatechang', function () {if (request. readyState = 4) {// readyState DONE // stores binary data. If localStorage is used, localForage cannot be implemented. setItem ('user _ incluphoto ', request. response, function () {// The image has been saved. You can use it for any purposes}) ;}}); request. send ()

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

LocalForage. getItem ('user _ incluphoto ', function (photo) {// after obtaining the image data, you can create a data URI or use other methods to display the console. log (photo );});
Callbacks & Promises

If you do not like to use callback in your code, you can useES6 PromisesTo replace the callback parameter of localForage. Let's use the photo example above and see the code using Promises:

LocalForage. getItem ('user _ incluphoto '). then (function (photo) {// after obtaining the image data, you can create a data URI or other methods to display the console. log (photo );});
Cross-browser support

LocalForage supports all modern browsers (including IE8 and later ). Supported browsers and platforms are as follows:

  • Android Web Browser 2.1
  • Blackberry 7
  • Chrome 23(Google Chrome 4.0 with localStorage)
  • Chrome for Android 32
  • Firefox 10(Firefox 3.5 with localStorage)
  • Firefox for Android 25
  • Firefox OS 1.0
  • IE 10(IE 8 with localStorage)
  • IE Mobile 10
  • Opera 15(Operators' 10.5 with localStorage)
  • Opera Mobile 11
  • Phonegap/Apache Cordova 1.2.0
  • Safari 3.1(Effecdes Mobile Safari)

 

 

Articles you may be interested in
  • 10 popular Metro UI Bootstrap themes and templates
  • Select 12 excellent jQuery Ajax paging plug-ins and tutorials
  • 10 popular topic Bootstrap in Metro UI Style
  • 8 exquisite jQuery plug-ins for loading animations and progress bars
  • 35 exquisite CSS3 and HTML5 webpage templates are recommended

Link: localForage: easily implement offline Web storage via Mozilla

Source: Dream sky ◆ focus on front-end development technology ◆ share web design resources

This article from [dream sky (http://www.cnblogs.com/lhb25 )]

Related Article

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.