git 应用程序本身更新_构建一个渐进式Web应用程序:脱机Git趋势分析应用程序第1部分(概念和服务工作者)...

git 应用程序本身更新

I love mobile apps too, and it's one of those who was strong-headed about accepting the new technology that simplified building mobile apps with web technologies. This is ironical because I have a strong web engineering background, but for some sentimental reasons, I just thought things should stay in the boxes made for them.

我也喜欢移动应用程序,它是那些勇于接受采用Web技术简化构建移动应用程序的新技术的人之一。 具有讽刺意味的是,因为我拥有强大的Web工程背景,但是出于某些感性的原因,我只是认为事情应该留在为他们准备的盒子中。

Pressure from the community and ecosystem had led me into giving in and thinking out of the box. After much back and forth, there just might be something out there to not only make mobile experience design approachable but also create a happy story for our users.

来自社区和生态系统的压力使我不得不屈服于思考。 经过反复的探索,也许不仅仅可以使移动体验设计变得平易近人,还可以为我们的用户创造一个快乐的故事。

In fact, there is something out there that you need to meet -- Progressive Web App. After trying out this concept and the technology behind it, I'm not sure I will ever have a need to build a native mobile for most of my web projects. If you think you need such solution, then tag along while I get you started in this article.

实际上,您需要满足一些条件-Progressive Web App。 在尝试了此概念及其背后的技术之后,我不确定是否会为大多数Web项目构建本地移动设备。 如果您认为您需要这种解决方案,请在本文中为您提供帮助。

What we'll build:

我们将建立:

渐进式Web应用 ( Progressive Web Apps )

Think of Progressive Web Apps (PWA) as your typical web app but engineered to deliver a better offline experience to users. It answers the question: How can we get rid of the following offline error?

将渐进式Web应用程序(PWA)视为典型的Web应用程序,但旨在为用户提供更好的脱机体验。 它回答了以下问题:我们如何摆脱以下离线错误?

It's not just about getting rid of the offline error, but engaging the user with consumable contents while their connection is restored.

这不仅是要摆脱脱机错误,而且还要在恢复连接时让用户使用消耗性内容。

Progressive web apps are major concerns on mobile devices. Let's tell a user a story and see why.

渐进式Web应用程序是移动设备上的主要问题。 让我们告诉用户一个故事,看看原因。

在桌面浏览器上 (On Desktop Browsers)
  • The user reaches for her laptop (at home, school or office).

    用户伸手拿她的笔记本电脑(在家中,学校或办公室)。
  • Checks if connected to internet / Connects to internet

    检查是否已连接到互联网/已连接到互联网
  • Opens up your web app

    打开您的网络应用
在移动 (On Mobile)
  • User pulls phone off her bag

    用户将手机从包中取出
  • (Doesn't connect to / check for the internet. Hopefully 3G or even worse 2G is available on her way to work or her trip to rural areas)

    (不连接/检查互联网。希望在上班途中或去农村旅行时可以使用3G或更糟的2G)
  • Opens up your app

    打开您的应用

As you can see, their stories are different. The user on mobile might not have enough internet power. She might not even have an internet connection at all. The goal is to keep her happy, engage her while her internet is restored. If it's a poor connection like 2G, you can keep her engaged while you make the long trip of getting some fresh information for her from your server.

如您所见,他们的故事是不同的。 移动用户可能没有足够的互联网能力。 她甚至可能根本没有互联网连接。 目标是让她开心,在恢复互联网的同时与她互动。 如果像2G这样的连接质量较差,则可以在长时间从服务器上获取有关她的新信息的过程中保持她的参与。

This illustration will make more sense when we start building a demo.

当我们开始构建演示时,此插图将更有意义。

服务人员 ( Service Workers )

The driving force behind PWAs is service workers. If you need to keep a user engaged at offline scenarios, then you need "someone" to run a background routine when your web app is opened for the first time. That "someone" needs to gather contents/assets from your web app when the user is online for later usage (when offline).

PWA背后的驱动力是服务人员。 如果需要让用户参与脱机场景,那么当您的Web应用程序首次打开时,您需要“某人”来运行后台例程。 当用户在线时,该“某人”需要从您的Web应用程序中收集内容/资产,以供日后使用(离线时)。

It's like the farming during farming season and storing food to last till the next cycle. You can even relate it with the popular saying "make hay when the sun shines."

这就像农耕季节中的耕种,食物储存到下一个周期。 您甚至可以将其与流行语“阳光照耀下的干草”联系起来。

That "someone" in the background, that farmer in the farming season, or the person making hay when the sun shines is the Service Worker in PWA's case. This is what MDN thinks about service workers:

在PWA案中,背景中的“某人”,耕种季节中的那个农民或阳光普照的人是干草。 这是MDN 对服务人员的看法

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available.)

服务工作人员是根据原点和路径注册的事件驱动的工作人员。 它采用JavaScript文件的形式,该文件可以控制与其关联的网页/站点,以非常精细的方式拦截和修改导航和资源请求,以及缓存资源,从而使您可以完全控制应用在特定情况下的行为(最明显的情况是网络不可用时。)

Long story short, a service worker is some logic you create to be run in the background. It has no access to the DOM but can interact with other resources like IndexDB and the Fetch API.

简而言之,服务人员是您创建的一些要在后台运行的逻辑。 它无权访问DOM,但可以与其他资源(如IndexDB和Fetch API)进行交互。

Things to keep in mind before we dive in:

在潜水之前要记住的事情:

  • Service workers must be served over HTTPS (or Localhost).

    必须通过HTTPS(或Localhost)为服务工作者提供服务。
  • They are designed to be Async so you can't use XHR (but you can use Fetch) or localStorage

    它们被设计为异步的,因此您不能使用XHR(但可以使用Fetch)或localStorage
  • Their scope is relative to the containing path. Therefore a worker at demo/sw.js is scoped to demo. Another at demo/first/sw.js is scoped to first.

    它们的范围是相对于包含路径的。 因此, demo/sw.js的工作人员demo/sw.jsdemodemo/first/sw.js另一个demo/first/sw.js范围是first

手机或PWA ( Mobile or PWA )

If you can use Service Workers to gather contents for the use of offline, then you might never have a need for a mobile app. As long as your app is responsive and optimized for mobile users, have little or no need to interact with mobile hardware, then you should be fine with a PWA.

如果您可以使用Service Workers来收集内容以供脱机使用,那么您可能永远不需要移动应用程序。 只要您的应用程序能够针对移动用户进行响应并进行了优化,几乎不需要或不需要与移动硬件进行交互,那么使用PWA就可以了。

I took some time to go activate "Airplane Mode" on my phone and see how some apps behave. In the end, you can categorize them into three types:

我花了一些时间去激活手机上的“飞行模式”,并查看一些应用程序的行为。 最后,您可以将它们分为三种类型:

  • Offline: Does nothing at all when offline

    离线离线时不执行任何操作

Example: Coinbase

示例: Coinbase

Coinbase is just stuck at the loading spinner. It even got me wondering why such apps exist because there is no difference compared to what is on the web. Coinbase is not a financial app shows sensitive information in realtime, therefore, PWA might just be good for only serving its App Shell.

Coinbase只是停留在加载微调器上。 甚至让我想知道为什么存在这样的应用程序,因为与网络上的应用程序没有区别。 Coinbase不是一个金融应用程序,它实时显示敏感信息,因此,PWA可能仅适合于为其App Shell服务

An App Shell is that part of an app that does not contain dynamic content. Navigation menu, sidebars, background, app logo, etc. are app shell contents.

App Shell是应用程序中不包含动态内容的部分。 导航菜单,侧边栏,背景,应用程序徽标等是应用程序外壳的内容。

  • Offline: Shows warns you, shows App Shell but remains useless

    离线 :显示警告您,显示App Shell,但仍然无用

Example: Uber

示例: Uber

Uber shows some content hinting the user with what she could achieve (by showing an App Shell and a map) if she were connected and also letting her know she can't achieve those things because she is offline. Uber is a handy app, so this strategy makes a lot of sense for their scenario.

Uber会显示一些内容,以提示用户连接后可以实现的目标(通过显示App Shell和地图),还可以让用户知道由于她处于离线状态而无法实现这些目标。 Uber是一款方便的应用程序,因此这种策略对于他们的情况非常有意义。

  • Offline: Shows cached data (can also warn when disconnected):

    离线 :显示缓存的数据(断开连接时也可以发出警告):

Example: Medium

示例:中

Medium shows you cached content when offline. Some apps in this category (e.g., Instagram) even warn you when you're disconnected, so you don't expect so much from the app.

中显示离线时缓存的内容。 当您断开连接时,该类别中的某些应用程序(例如,Instagram)甚至会警告您,因此您对应用程序的期望并不高。

扣除 (Deduction)

My thoughts are, if PWA (and service workers) become matured enough and well accepted, why not save our users the stress of 1, going to the app store and 2, downloading apps they might not always use. When we discuss Web Manifest in the 3rd part of this tutorial, you will learn that you can add a home screen icon for you web app with which the web app can be launched.

我的想法是,如果PWA(和服务人员)变得足够成熟并受到广泛接受,为什么不为我们的用户省去1,去应用商店和2,下载他们可能不经常使用的应用的压力。 当我们在本教程的第3部分中讨论Web清单时,您将了解到可以为Web应用程序添加一个主屏幕图标,从而可以启动该Web应用程序。

Some businesses are already doing great with PWA, and you can learn about them at pwa.rocks:

一些企业已经在PWA方面做得很好,您可以在pwa.rocks上了解它们:

准备演示 ( Preparing Demo )

We have done a lot of talking already. This is a hands-on tutorial, so it's time to get our hands dirty now that some of the concepts have been explained. First, create a fresh project with the following structure:

我们已经做了很多讨论。 这是一个动手教程,因此,既然已经解释了一些概念,现在该让我们动手了。 首先,使用以下结构创建一个新项目:

|--pwa-demo
|----css
|----fonts
|----images
|----js
|----index.html
|----service-worker.js

Download Materialize material design UI library and copy the CSS, Fonts, and JS assets into the pwa-demo replacing the existing folders.

下载Materialise材质设计UI库,然后将CSS, pwa-demo 和JS资源复制到pwa-demo以替换现有文件夹。

Open index.html and setup a basic template to include the added assets:

打开index.html并设置一个基本模板以包括添加的资产:

<!-- ./index.html -->
<!DOCTYPE html>
  <html>
    <head>
      <!--Import Google Icon Font-->
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <!--Import materialize.css-->
      <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>
      <link type="text/css" rel="stylesheet" href="css/app.css">

      <!--Let browser know website is optimized for mobile-->
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>

    <body>

      Body coming soon

      <!-- Scripts -->
      <script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
      <script type="text/javascript" src="js/materialize.min.js"></script>
      <script type="text/javascript" src="js/app.js"></script>
    </body>
  </html>

We have imported all the downloaded assets as well as an app.js custom JavaScript file which we are yet to create.

我们已经导入了所有下载的资源以及尚未创建的app.js自定义JavaScript文件。

注册服务人员 ( Registering Service Worker )

For service workers to work, you need to tell the browser of course. This is best done as early as possible. If possible at your Project's entry point. We can register a new worker in app.js:

为了让服务人员正常工作,您当然需要告诉浏览器。 最好尽早完成。 如果可能,在项目的入口点。 我们可以在app.js注册一个新的worker:

(function(){
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker
     .register('/service-worker.js')
     .then(function() { 
        console.log('Service Worker Registered'); 
      });
  }    
})()

First, we check if the browser supports service worker before attempting anything else related to this feature. If it does, then we can go ahead to register it with the register method which takes the path to the service worker file. Registration returns a promise where you can find out if it was successful or not.

首先,我们在尝试与此功能相关的任何其他操作之前,先检查浏览器是否支持服务工作者。 如果是这样,那么我们可以继续使用register方法注册它,该方法采用服务工作者文件的路径。 注册会返回一个承诺,您可以在其中查看成功与否。

服务人员生命周期 ( Service Worker Lifecycle )

Service workers have a lifecycle which you need to understand at the very beginning of your journey:

服务人员有一个生命周期,在旅途的一开始就需要了解它:

安装 (Install)

This stage is where a worker is installed in the browser for a given scope. Take advantage of this stage to cache all your assets as early as possible because this is the first stage of the lifecycle:

此阶段是在给定范围内在浏览器中安装工作程序的位置。 请利用此阶段来尽早缓存所有资产,因为这是生命周期的第一阶段:

// ./service-worker.js

var cacheName = 'PWADemo-v1';
var filesToCache = [
  '/index.html',
  '/css/app.css',
  '/js/app.js',
  /* ...and other assets (jQuery, Materialize, fonts, etc) */
];

self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    })
  );
});
  • caches.open and cache.addAll are async operations and the service worker could terminate before these operations are completed. e.waitUntil asks the service worker to wait while the promise is resolved/rejected.

    caches.opencache.addAll是异步操作,服务工作者可以在这些操作完成之前终止。 e.waitUntil要求服务工作者在承诺被兑现/拒绝时等待。
  • When the cache is opened, we try to add the assets to the cache with addAll

    打开缓存后,我们尝试使用addAll将资产添加到缓存中
  • Keep in mind that if any of the files fail to be cached (may because it's probably missing), the service worker will fail to install.

    请记住,如果无法缓存任何文件(可能是因为可能丢失了),则服务程序将无法安装。

启用 (Activate)

When changes are made, and service worker is updated, they are not immediately reflected until all sessions with the previous service worker are closed and the app re-visited. Assuming we register another service worker with a different cache name by updating the cache version string:

进行更改并更新Service Worker之后,直到与前一个Service Worker的所有会话都关闭并且重新访问该应用程序后,这些更改才会立即反映出来。 假设我们通过更新缓存版本字符串来注册另一个具有不同缓存名称的服务工作者:

// ./service-worker.js

var cacheName = 'PWADemo-v2';
var filesToCache = [
  //...
];

self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  //...
});

When the new service worker is created, a new cache PWADemo-v2 will be created, but PWADemo-v1 will still be there. When activate is triggered, PWADemo-v2 takes over making this stage a good place to delete PWADemo-v1:

创建新的服务工作者后,将创建新的缓存PWADemo-v2 ,但PWADemo-v1仍将存在。 触发激活后, PWADemo-v2将接管此阶段,成为删除PWADemo-v1的好地方:

// ./service-worker.js

self.addEventListener('activate', function(e) {
  console.log('[ServiceWorker] Activate');
  e.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (key !== cacheName) {
          console.log('[ServiceWorker] Removing old cache', key);
          return caches.delete(key);
        }
      }));
    })
  );
});

We check for all the cache names that don't match the current cache in use and delete them.

我们检查所有与当前使用中的缓存不匹配的缓存名称,并删除它们。

(Fetch)

Fetch is not necessary a lifecycle hook but an event to intercept requests for assets. When a request is encountered, it first goes through this event:

提取不是必需的生命周期挂钩,而是用于拦截资产请求的事件。 遇到请求时,它首先会经历以下事件:

// ./service-worker.js

self.addEventListener('fetch', function(e) {
  console.log('[ServiceWorker] Fetch', e.request.url);
  e.respondWith(
    caches.match(e.request).then(function(response) {
      return response || fetch(e.request);
    })
  );
});

If the asset is already cached, then we respond the browser with the cached version. If that's not the case, we use the fetch API to make an actual HTTP request for the asset.

如果资产已经被缓存,则我们用缓存的版本响应浏览器。 如果不是这种情况,我们将使用fetch API对资产进行实际的HTTP请求。

调试服务人员 ( Debugging Service Workers )

Service workers are not so easy to debug because of how they work, especially when caching. Fortunately, Chrome Dev Tool provides a helpful service worker debugging feature. Take the following steps to inspect our just registered service worker:

由于服务人员的工作方式(特别是在缓存时),调试起来并不容易。 幸运的是,Chrome开发工具提供了有用的服务人员调试功能。 请采取以下步骤检查我们刚刚注册的服务人员:

  • Open Chrome Dev Tool

    开启Chrome开发工具
  • Navigate to the Applications tab and open service worker section:

    导航到“应用程序”选项卡并打开“服务工作者”部分:

  • You can see the status flag in green showing that your service worker is fine:

    您可以看到绿色的状态标志,表明您的服务人员状况良好:

  • You can check "Update on reload" to forcefully update the service worker without having to close all your existing sessions:

    您可以选中“重新加载时更新”以强制更新服务工作者,而不必关闭所有现有会话:

  • Right click on "Cache Storage" and click refresh to see your list of caches. Open the one with your cache name, and you will see the list of items in the cache:

    右键单击“缓存存储”,然后单击“刷新”以查看您的缓存列表。 用您的缓存名称打开一个,您将看到缓存中的项目列表:

下一个 ( Next Up )

The PWA concept is no longer new to you. You have already learned what you need to know to get started. In the next post, we are going to discuss caching and caching strategies you could employ when building PWAs. We will also see how to use IndexDB to persist data and not localStorage. The reason for this choice will also be highlighted.

PWA概念对您而言已不再是新鲜事物。 您已经学会了入门所需的知识。 在下一篇文章中,我们将讨论构建PWA时可以使用的缓存和缓存策略。 我们还将看到如何使用IndexDB持久化数据,而不是localStorage。 选择该选项的原因也将突出显示。

翻译自: https://scotch.io/tutorials/build-a-progressive-web-app-offline-git-trending-app-part-1-concepts-and-service-workers

git 应用程序本身更新

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值