渐进式网站应用会很快启动并马上可用。在目前的状态中(step-04),我们的天气app启动很快,但是不可用。因为还木有数据。 我们要使用一个AJAX请求去获取数据,但是这会导致一个额外的请求,并使初始加载时间更长。但仍然要在第一次加载时提供真实的数据。
对于这个代码实验室,我们将模拟服务器将天气预报直接注入到JavaScript中,但在生产应用程序的过程中,最新的天气预报数据将由服务器根据用户的IP地址地理位置注入。
代码中已经包含数据并且我们将要进行注入,就是这个 initialWeatherForecast
方法,我们开始使用下一个步骤。
但是,我们如何知道什么时候显示这些信息,当天气应用程序从缓存中提取时,这些信息可能与未来的载入无关?当用户在后续访问中加载应用程序时,他们可能已经改变了城市,所以我们需要加载这些城市的信息,而不一定是他们的第一个次查找的那个城市。
用户首选项(如用户已订阅的城市列表)应使用IndexedDB或其他快速存储机制进行本地存储。为了尽可能简化这个代码实验,我们使用了 localStorage
, 这对生产应用程序来说并不理想,因为它是一个阻塞的同步存储机制,在某些设备上可能非常慢。
额外的提示: 利用idb替换localStorage
来实现, 确保localForage做为idb的一个简单包装。
首先,我们添加保存用户设置的所需要的代码在你的代码中找到下面所示的 TODO 注视。
// TODO add saveSelectedCities function here
在注视下面添加下列代码。
// Save list of cities to localStorage.
app.saveSelectedCities = function() {
var selectedCities = JSON.stringify(app.selectedCities);
localStorage.selectedCities = selectedCities;
};
接下来,我们添加启动代码来检查用户是否有任何已保存了城市并渲染它们,或使用注入的数据。找到以下注释:
// TODO add startup code here
在注视下面添加下列代码:
/************************************************************************
*
* Code required to start the app
*
* NOTE: To simplify this codelab, we've used localStorage.
* localStorage is a synchronous API and has serious performance
* implications. It should not be used in production applications!
* Instead, check out IDB (https://www.npmjs.com/package/idb) or
* SimpleDB (https://gist.github.com/inexorabletash/c8069c042b734519680c)
************************************************************************/
app.selectedCities = localStorage.selectedCities;
if (app.selectedCities) {
app.selectedCities = JSON.parse(app.selectedCities);
app.selectedCities.forEach(function(city) {
app.getForecast(city.key, city.label);
});
} else {
/* The user is using the app for the first time, or the user has not
* saved any cities, so show the user some fake data. A real app in this
* scenario could guess the user's location via IP lookup and then inject
* that data into the page.
*/
app.updateForecastCard(initialWeatherForecast);
app.selectedCities = [
{key: initialWeatherForecast.key, label: initialWeatherForecast.label}
];
app.saveSelectedCities();
}
启动代码检查是否有任何城市保存在本地存储。如果是,则解析本地存储数据,然后为每个保存的城市显示天气预报卡。如果否,则启动代码只是使用虚假预测数据,并将其保存为默认城市。
最后,您需要修改“添加城市”按钮程序,将选定的城市保存到本地存储
更新你的 butAddCity
点击程序,使它和下面的代码一样:
document.getElementById('butAddCity').addEventListener('click', function() {
// Add the newly selected city
var select = document.getElementById('selectCityToAdd');
var selected = select.options[select.selectedIndex];
var key = selected.value;
var label = selected.textContent;
if (!app.selectedCities) {
app.selectedCities = [];
}
app.getForecast(key, label);
app.selectedCities.push({key: key, label: label});
app.saveSelectedCities();
app.toggleAddDialog(false);
});
新增了 app.selectedCities
的初始化,如果不存在,就调用 app.selectedCities.push()
和 app.saveSelectedCities()方法
。
initialWeatherForecast
立即显示用户的天气预报本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。