在上一篇,介绍一下渐进式 Web App(离线) - Part 1的文章中,咱们讨论了典型的pwa应该是什么样子的而且同时也介绍了 server worker。到目前为止,咱们已经缓存了应用壳。在 index.html
和latet.html
页面中,咱们的应用已经实现了离线加载缓存数据。在重复访问时,它们的加载速度更快。在本教程第一部分的结尾,咱们可以离线加载latest.html
,但在用户离线时没法显示得到动态数据。此次学习咱们将:html
latest
页面缓存 app的数据localStorage
去存储 app 的数据在构建PWA时,须要考虑各类存储机制:git
indexDB在浏览器的兼容性github
Web Storage 的浏览器兼容表web
根据PouchDB的维护者 Nolan Lawson说,在使用数据库时,最好问本身这些问题:数据库
您能够查看考虑如何选择数据库,以便更全面地了解主题内容。apache
在咱们的 web app 中,咱们将用localStorage
,因为我在本教程前面强调的局限性,我建议你不要在生产环境中使用localStorage
。咱们正在构建的应用程序很是简单,因此是使用了localStorage
。npm
打开你的js/latest.js
文件,咱们更新fetchCommits
方法去存储从 Github API
拉取的数据,存储在localStorage
。代码以下:json
function fetchCommits() { var url = 'https://api.github.com/repos/unicodeveloper/resources-i-like/commits'; fetch(url) .then(function(fetchResponse){ return fetchResponse.json(); }) .then(function(response) { console.log("Response from Github", response); var commitData = {}; for (var i = 0; i < posData.length; i++) { commitData[posData[i]] = { message: response[i].commit.message, author: response[i].commit.author.name, time: response[i].commit.author.date, link: response[i].html_url }; } localStorage.setItem('commitData', JSON.stringify(commitData)); for (var i = 0; i < commitContainer.length; i++) { container.querySelector("" + commitContainer[i]).innerHTML = "<h4> Message: " + response[i].commit.message + "</h4>" + "<h4> Author: " + response[i].commit.author.name + "</h4>" + "<h4> Time committed: " + (new Date(response[i].commit.author.date)).toUTCString() + "</h4>" + "<h4>" + "<a href='" + response[i].html_url + "'>Click me to see more!</a>" + "</h4>"; } app.spinner.setAttribute('hidden', true); // hide spinner }) .catch(function (error) { console.error(error); }); };
上面有这段代码,在第一页加载的时候,这些提交的数据就存储到localStorage
了,如今咱们写另一个函数去渲染这些localStorage
的数据。代码以下:segmentfault
// Get the commits Data from the Web Storage function fetchCommitsFromLocalStorage(data) { var localData = JSON.parse(data); app.spinner.setAttribute('hidden', true); //hide spinner for (var i = 0; i < commitContainer.length; i++) { container.querySelector("" + commitContainer[i]).innerHTML = "<h4> Message: " + localData[posData[i]].message + "</h4>" + "<h4> Author: " + localData[posData[i]].author + "</h4>" + "<h4> Time committed: " + (new Date(localData[posData[i]].time)).toUTCString() + "</h4>" + "<h4>" + "<a href='" + localData[posData[i]].link + "'>Click me to see more!</a>" + "</h4>"; } };
这段代码将数据从本地存储并将其渲染 dom 节点。api
如今咱们须要知道,什么条件去调用fetchCommits
函数和fetchCommitsFromLocalStorage
函数。
js/latest.js
代码以下
(function() { 'use strict'; var app = { spinner: document.querySelector('.loader') }; var container = document.querySelector('.container'); var commitContainer = ['.first', '.second', '.third', '.fourth', '.fifth']; var posData = ['first', 'second', 'third', 'fourth', 'fifth']; // Check that localStorage is both supported and available function storageAvailable(type) { try { var storage = window[type], x = '__storage_test__'; storage.setItem(x, x); storage.removeItem(x); return true; } catch(e) { return false; } } // Get Commit Data from Github API function fetchCommits() { var url = 'https://api.github.com/repos/unicodeveloper/resources-i-like/commits'; fetch(url) .then(function(fetchResponse){ return fetchResponse.json(); }) .then(function(response) { console.log("Response from Github", response); var commitData = {}; for (var i = 0; i < posData.length; i++) { commitData[posData[i]] = { message: response[i].commit.message, author: response[i].commit.author.name, time: response[i].commit.author.date, link: response[i].html_url }; } localStorage.setItem('commitData', JSON.stringify(commitData)); for (var i = 0; i < commitContainer.length; i++) { container.querySelector("" + commitContainer[i]).innerHTML = "<h4> Message: " + response[i].commit.message + "</h4>" + "<h4> Author: " + response[i].commit.author.name + "</h4>" + "<h4> Time committed: " + (new Date(response[i].commit.author.date)).toUTCString() + "</h4>" + "<h4>" + "<a href='" + response[i].html_url + "'>Click me to see more!</a>" + "</h4>"; } app.spinner.setAttribute('hidden', true); // hide spinner }) .catch(function (error) { console.error(error); }); }; // Get the commits Data from the Web Storage function fetchCommitsFromLocalStorage(data) { var localData = JSON.parse(data); app.spinner.setAttribute('hidden', true); //hide spinner for (var i = 0; i < commitContainer.length; i++) { container.querySelector("" + commitContainer[i]).innerHTML = "<h4> Message: " + localData[posData[i]].message + "</h4>" + "<h4> Author: " + localData[posData[i]].author + "</h4>" + "<h4> Time committed: " + (new Date(localData[posData[i]].time)).toUTCString() + "</h4>" + "<h4>" + "<a href='" + localData[posData[i]].link + "'>Click me to see more!</a>" + "</h4>"; } }; if (storageAvailable('localStorage')) { if (localStorage.getItem('commitData') === null) { /* The user is using the app for the first time, or the user has not * saved any commit data, so show the user some fake data. */ fetchCommits(); console.log("Fetch from API"); } else { fetchCommitsFromLocalStorage(localStorage.getItem('commitData')); console.log("Fetch from Local Storage"); } } else { toast("We can't cache your app data yet.."); } })();
在上面的代码片段,咱们正在检查浏览器是否支持本地存储,若是它支持,咱们继续检查是否已经缓存了提交数据。若是没有被缓存,咱们将请求数据,显示到页面上而且缓存请求的数据。
如今,重新刷新一遍浏览器,确保你作了一个清晰的缓存,强制刷新,不然咱们不会看到咱们的代码更改的结果。
如今,离线并加载最新页面。将发生了什么事呢?
Yaaay!!! 它加载数据没有任何问题。
查看DevTools
,你间看到数据已经被缓存到localStorage
当用户离线时,看看它加载的速度!!!
如今,咱们能够当即从本地存储获取数据。可是咱们如何得到最新的数据?当用户在线时,咱们须要一种仍然得到新数据的方法。
so easy, 让咱们添加一个刷新按钮,触发一个请求到GitHub得到的最新数据。
打开latest.html
文件,而且添加一个刷新按钮到<header>
标签
<button id="butRefresh" class="headerButton" aria-label="Refresh"></button>
添加的按钮后<header>
标签应该是这样的:
<header> <span class="header__icon"> <svg class="menu__icon no--select" width="24px" height="24px" viewBox="0 0 48 48" fill="#fff"> <path d="M6 36h36v-4H6v4zm0-10h36v-4H6v4zm0-14v4h36v-4H6z"></path> </svg> </span> <span class="header__title no--select">PWA - Commits</span> <button id="butRefresh" class="headerButton" aria-label="Refresh"></button> </header>
最后,让咱们在按钮上附加一个单击事件并添加功能。打开js/latest.js
而且添加以下代码:
document.getElementById('butRefresh').addEventListener('click', function() { // Get fresh, updated data from GitHub whenever you are clicked toast('Fetching latest data...'); fetchCommits(); console.log("Getting fresh data!!!"); });
清除缓存并从新加载。如今,你的latest.html
页面看起来应该像这样:
每当用户须要最新数据时,他们只需单击刷新按钮便可。
附加:
点击查看下面连接
上一篇: 译介绍一下渐进式 Web App(离线) - Part 1
若是有那个地方翻译出错或者失误,请各位大神不吝赐教,小弟感激涕零
期待下一篇: 介绍一下渐进式 Web App(消息推送) - Part 3