[PWA] 15. Using the IDB Cache and Display Entries

Source: Internet
Author: User

We want to use IDB to store the wittr messages.

The logic is when the page start:

    1. Service worker would read the skeleton from the cache and show to the interface.
    2. Read the message data from the IDB first instead by going to network.
    3. Show the data from IDB then open socket to fetch updated wittr.
    4. Once data arrive, update the interface and save into IDB.

Exportdefault functionIndexcontroller (container) { This. _container =container;  This. _postsview =NewPostsview ( This. _container);  This. _toastsview =NewToastsview ( This. _container);  This. _lostconnectiontoast =NULL; This  . _opensocket ();   this. _dbpromise = OpenDatabase ();    This . _registerserviceworker ();}

In OpenDatabase (), we create WITTR DB, set ID as primary key and time as index called ' By-time '

function OpenDatabase () {  //  If The browser doesn ' t support Service worker,  //  We don ' t care on having a database  if (!  Navigator.serviceworker) {    return  promise.resolve ();  }    return function (upgradedb) {      = Upgradedb.createobjectstore (' wittrs ', {        ' id '      });    Store.createindex (' by-date ', ' time ');  });

In _opensocket, we had a function to fetch the old data from the IDB.

// Open a connection to the server for live updates function () {

... Ws.addeventlistener (function(event) { requestanimationframe() { Indexcontroller. _onsocketmessage (event.data); }); ...};

//called when the Web socket sends message dataIndexcontroller.prototype._onsocketmessage =function(data) {varMessages =json.parse (data);  This. _dbpromise.then (function(db) {if(!DB)return; //todo:put each message into the ' Wittrs '    //Object store.CONST TX = db.transaction (' wittrs ', ' ReadWrite '); Const WITTRS= Tx.objectstore (' Wittrs '); Messages.foreach (message)={wittrs.put (message);    }); returnTx.complete;  });  This. _postsview.addposts (messages);};

[PWA] 15. Using the IDB Cache and Display Entries

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.