From 310fd066e91f454b990372ffa30e803cc8120975 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 12:56:40 +0100 Subject: unslug zh-cn: move --- .../add_to_home_screen/index.html | 218 ++++++++++++ .../web/progressive_web_apps/loading/index.html | 152 ++++++++ .../network_independent/index.html | 95 ----- .../progressive_web_apps/re-engageable/index.html | 79 ----- .../web/progressive_web_apps/responsive/index.html | 78 ---- .../responsive/media_types/index.html | 391 +++++++++++++++++++++ .../\344\274\230\345\212\277/index.html" | 58 --- .../\345\212\240\350\275\275/index.html" | 152 -------- .../index.html" | 218 ------------ 9 files changed, 761 insertions(+), 680 deletions(-) create mode 100644 files/zh-cn/web/progressive_web_apps/add_to_home_screen/index.html create mode 100644 files/zh-cn/web/progressive_web_apps/loading/index.html delete mode 100644 files/zh-cn/web/progressive_web_apps/network_independent/index.html delete mode 100644 files/zh-cn/web/progressive_web_apps/re-engageable/index.html delete mode 100644 files/zh-cn/web/progressive_web_apps/responsive/index.html create mode 100644 files/zh-cn/web/progressive_web_apps/responsive/media_types/index.html delete mode 100644 "files/zh-cn/web/progressive_web_apps/\344\274\230\345\212\277/index.html" delete mode 100644 "files/zh-cn/web/progressive_web_apps/\345\212\240\350\275\275/index.html" delete mode 100644 "files/zh-cn/web/progressive_web_apps/\346\267\273\345\212\240\345\210\260\344\270\273\345\261\217\345\271\225/index.html" (limited to 'files/zh-cn/web/progressive_web_apps') diff --git a/files/zh-cn/web/progressive_web_apps/add_to_home_screen/index.html b/files/zh-cn/web/progressive_web_apps/add_to_home_screen/index.html new file mode 100644 index 0000000000..a0915ea9d2 --- /dev/null +++ b/files/zh-cn/web/progressive_web_apps/add_to_home_screen/index.html @@ -0,0 +1,218 @@ +--- +title: 添加到主屏幕 +slug: Web/Progressive_web_apps/添加到主屏幕 +tags: + - PWA + - 图标 + - 服务进程 + - 添加到主屏幕 + - 清单 + - 渐进式Web应用 +translation_of: Web/Progressive_web_apps/Add_to_home_screen +--- +

添加到主屏幕(A2HS)添加到主屏幕(简称A2HS)是现代智能手机浏览器中的一项功能,使开发人员可以轻松便捷地将自己喜欢的Web应用程序(或网站)的快捷方式添加到主屏幕中,以便他们随后可以通过单点访问它。本指南说明了A2HS的使用方式,以及作为开发人员要使您的用户利用A2HS所需做的事情。

+ +

为什么选择A2HS?

+ +

A2HS被认为是渐进式Web应用程序哲学的一部分—为Web应用程序提供与原生应用程序相同的用户体验优势,因此它们可以在当今的生态系统战争中竞争。这部分是通过访问主屏幕上的应用程序图标来访问应用程序,然后将其整齐地显示在自己的窗口中的简单手势。A2HS使这成为可能。

+ +

哪些浏览器支持A2HS?

+ +

Mobile Chrome / Android Webview 从31版开始支持A2HS,Opera for Android从32版开始支持,Firefox for Android从58版开始支持。

+ +

如何使用?

+ +

我们已经编写了一个非常简单的示例网站(观看我们的在线演示,并查看源代码),该网站虽然功能不多,但是开发时使用了必要的代码,也可以将其添加到主屏幕中,并且service worker使其可以脱机使用。这个示例展示了一系列的狐狸图片。

+ +

如果您有适用于Android的Firefox,使用它导航到我们的示例:https://mdn.github.io/pwa-examples/a2hs/。你将会看到狐狸图片,但更重要的是,你将会看到一个带有加号(+)的“主页”图标—这是为具有必要功能的任何站点显示的“添加到主屏幕”图标。

+ +

+ +

点击此按钮将显示一个确认横幅—按下大“+ 添加到主屏幕”按钮即可完成操作,将应用添加到主屏幕。(注意:在Android 8及更高版本中,将首先显示系统级的“添加到主屏幕”权限对话框。)

+ +

+ +

如果您可以使用Mobile Chrome,则体验会略有不同;加载我们的网站后,您会看到一个弹出安装横幅,询问您是否要将此应用添加到主屏幕。

+ +

+ +
+

注意:您可以在“Web App安装横幅”一文中找到有关Chrome安装横幅的更多信息。

+
+ +

如果您选择不将其添加到主屏幕,则可以稍后使用Chrome主菜单中的添加到主屏幕图标添加。

+ +

无论使用哪种浏览器,当您选择将应用程序添加到主屏幕时,您都会看到它与短标题一起出现,就像原生应用程序一样。

+ +

+ +

点按此图标可以将其打开,但是作为全屏应用程序,您将不再看到其周围的浏览器用户界面。

+ +

如何使应用程序支持A2HS?

+ +

要将您的应用添加到主屏幕,它需要满足以下条件:

+ + + +

Manifest

+ +

web manifest 以标准JSON格式编写,应放置在应用程序目录中的某个位置(最好是在根目录中),名称为somefilename.webmanifest(我们选择 manifest.webmanifest)。它包含多个字段,这些字段定义有关Web应用程序及其行为的某些信息。

+ +
+

注意:.webmanifest扩展名是在规范的“媒体类型注册”部分中指定的,但通常浏览器将支持带有其他适当扩展名的清单,例如:.json。

+
+ +

A2HS所需的字段如下:

+ + + +

我们的示例应用程序的manifest如下所示:

+ +
{
+  "background_color": "purple",
+  "description": "Shows random fox pictures. Hey, at least it isn't cats.",
+  "display": "fullscreen",
+  "icons": [
+    {
+      "src": "icon/fox-icon.png",
+      "sizes": "192x192",
+      "type": "image/png"
+    }
+  ],
+  "name": "Awesome fox pictures",
+  "short_name": "Foxes",
+  "start_url": "/pwa-examples/a2hs/index.html"
+}
+ +

合适的图标

+ +

如以上manifest所示,我们包括一个192 x 192像素的图标,供我们的应用使用。您可以根据需要添加更多尺寸;Android将为每个不同的用例选择最合适的尺寸。您还可以决定添加不同类型的图标,以便设备可以使用他们能够使用的最佳图标(例如,Chrome已经支持WebP格式).

+ +

请注意,每个图标对象中的 type 成员都指定了该图标的mimetype,因此浏览器可以快速读取该图标的类型,然后将其忽略,并在不支持该图标时采用其他图标。

+ +

在设计图标方面,您应该遵循与任何Android图标相同的最佳做法(请参阅Android图标设计指南)。

+ +

将HTML链接到manifest

+ +

要完成manifest的设置,您需要从应用程序主页的 HTML 中引用它:

+ +
<link rel="manifest" href="manifest.webmanifest">
+ +

一旦支持 manifest,支持 A2HS 的浏览器就会知道在哪里查找它。

+ +

A2HS没有给你什么?

+ +

请记住,将应用程序添加到主屏幕时,它只会使该应用程序易于访问—不会将应用程序的资产和数据下载到您的设备上,也不会使该应用程序脱机使用或类似的操作。 为了使你的应用离线运行,你必须使用Service Worker API来离线存储资源,如果需要,还可以使用 Web storage 或 IndexedDB 来存储其数据。

+ +

在示例应用程序中,我们仅使用了一个service worker来存储所有必需的文件。service worker使用index.js 文件中的最终的代码块在网站上注册。然后,我们使用 Cache API 缓存网站的所有资产,并使用 sw.js 文件中的代码从缓存而不是网络中为它们提供服务。

+ +

桌面上的A2HS

+ +

虽然最初旨在改善移动操作系统上的用户体验,但人们也提出了使PWA也可以安装在桌面平台上的趋势。

+ +
+

注意:在撰写本文时,仅在较新版本的Chrome(在Windows中默认情况下,在macOS上的#enable-desktop-pwas标志开启后)中支持以下功能。

+
+ +

添加安装按钮

+ +

为了使PWA可在桌面上安装,我们首先在文档中添加了一个按钮,以允许用户进行安装—桌面应用程序不会自动提供此按钮,并且需要通过用户手势来触发安装:

+ +
<button class="add-button">Add to home screen</button>
+ +

然后,我们给它一些简单的样式:

+ +
.add-button {
+  position: absolute;
+  top: 1px;
+  left: 1px;
+}
+ +

用于处理安装的JavaScript

+ +

index.js文件的底部,我们添加了一些JavaScript来处理安装。首先,我们声明一个deferredPrompt变量(我们将在后面解释),获得对安装按钮的引用,并初始设置为display: none

+ +
let deferredPrompt;
+const addBtn = document.querySelector('.add-button');
+addBtn.style.display = 'none';
+ +

我们最初隐藏该按钮是因为PWA必须遵循A2HS标准才能安装。发生这种情况时,支持的浏览器将触发beforeinstallprompt事件。 然后,我们可以使用以下处理程序来处理安装:

+ +
window.addEventListener('beforeinstallprompt', (e) => {
+  // Prevent Chrome 67 and earlier from automatically showing the prompt
+  e.preventDefault();
+  // Stash the event so it can be triggered later.
+  deferredPrompt = e;
+  // Update UI to notify the user they can add to home screen
+  addBtn.style.display = 'block';
+
+  addBtn.addEventListener('click', (e) => {
+    // hide our user interface that shows our A2HS button
+    addBtn.style.display = 'none';
+    // Show the prompt
+    deferredPrompt.prompt();
+    // Wait for the user to respond to the prompt
+    deferredPrompt.userChoice.then((choiceResult) => {
+        if (choiceResult.outcome === 'accepted') {
+          console.log('User accepted the A2HS prompt');
+        } else {
+          console.log('User dismissed the A2HS prompt');
+        }
+        deferredPrompt = null;
+      });
+  });
+});
+ +

所以我们在这里:

+ + + +

点击处理程序包含以下步骤:

+ + + +

So when the button is clicked, the install prompt appears.

+ +

+ +

如果用户选择安装,则将安装该应用程序(可作为独立的桌面应用程序使用),并且不再显示“安装”按钮(如果已经安装了该应用程序,则将不再触发onbeforeinstallprompt事件)。当您打开应用程序时,它将显示在其自己的窗口中:

+ +

+ +

如果用户选择“取消”,则应用程序的状态将返回到单击按钮之前的状态。

+ +
+

注意:本部分的代码主要来自Pete LaPage的应用安装横幅/添加到主屏幕

+
+ +

其他

+ + + +
{{QuickLinksWithSubpages("/en-US/docs/Web/Progressive_web_apps/")}}
diff --git a/files/zh-cn/web/progressive_web_apps/loading/index.html b/files/zh-cn/web/progressive_web_apps/loading/index.html new file mode 100644 index 0000000000..7f45a3c278 --- /dev/null +++ b/files/zh-cn/web/progressive_web_apps/loading/index.html @@ -0,0 +1,152 @@ +--- +title: 渐进式加载 +slug: Web/Progressive_web_apps/加载 +tags: + - PWA + - 渐进式加载 +translation_of: Web/Progressive_web_apps/Loading +--- +
{{PreviousMenu("Web/Apps/Progressive/Re-engageable_Notifications_Push", "Web/Apps/Progressive")}}
+ +

在前面的文章我们介绍了很多api,例如:Service Workers, Web Manifests, Notifications and Push,它让我们的示例应用 js13kPWA 成为一个渐进式web应用。在这篇文章里我们将会走得更远,我们会使用资源渐进式加载来提高整个应用的性能。

+ +

首次有效渲染

+ +

尽快把有效的信息输送给用户是一件非常重要的事情 —— 等待页面加载的时间越长,用户在页面加载完成之前离开的概率就越大。为了达到这个目的,网页加载完成前,我们应该用占位符在最终资源将会加载的地方展示最起码的视图骨架。

+ +

这个功能可以用渐进式加载来实现 —— 它也被称为 懒加载。它的做法是延迟加载尽可能多的资源(HTML, CSS, JavaScript),只有在用户第一次使用到它的时候,它才会被立刻加载。

+ +

打包还是拆分

+ +

大部分的用户不会用到一个网站的所有页面,但我们通常的做法却是把我们所有的功能都打包进一个很大的文件里面。一个 bundle.js 文件的大小可能会有几个M,一个打包后的style.css 会包含一切东西,从CSS结构定义到各个版本的网站的样式:移动端,平板,桌面,打印等等。

+ +

通常来说只加载一个打包后大的文件会比加载很多个小文件要快一些,但如果用户并不是一开始就需要所有的资源,我们就可以首先加载那些关键的资源,其他的等到我们需要的时候,我们再去加载它。

+ +

导致页面阻塞的资源(Render-blocking resources)

+ +

将所有文件打包是一种不好的做法,因为浏览器把计算结果渲染到屏幕之前,需要先把HTML,CSS和JavaScript下载下来。在页面被打开到页面加载完成的这段时间里,用户将会看到一个空白的页面,这无疑是一个非常糟糕的体验。

+ +

为了解决这个问题,举个例子,我们可以在script标签上面加上一个 defer

+ +
<script src="app.js" defer></script>
+
+ +

他们会等到文档解析完成之后再开始下载和执行,所以他们不会阻塞HTML页面的渲染。我们还可以拆分css文件并给它们加上media属性:

+ +
<link rel="stylesheet" href="style.css">
+<link rel="stylesheet" href="print.css" media="print">
+
+ +

 这种做法告诉浏览器只有在条件满足的情况下才加载这些资源(例如指定了print,则在打印环境下才会加载这些资源,译者注)。

+ +

在我们这个js13kPWA应用里面,由于CSS非常的简单,因此所有样式都被放到一个文件里面,并没有具体的规则来指导它如何加载css。但我们可以做得更好,例如把 style.css 里面的所有内容移动到一个 <style> 标签里面,并把它放到 index.html  的 <head> 的里面。这样做可以进一步提高应用的性能,但为了使代码更具可读性,我们并没有选择这么做。

+ +

图片

+ +

除了JavaScript和CSS,网站通常还会包含大量的图片。当你把{{htmlelement("img")}}元素添加到网站里面时,对应的所有图片资源都会在页面初始化时被下载下来。在网站就绪之前下载几个兆的图片资源是一种比较常见的状况,但它会再次给人一种性能不好的印象。我们并不需要在一打开网站的时候就以最高的画质呈现所有的图片。

+ +

这是可以优化的。首先,你可以使用类似TinyPNG这类工具或者服务,它可以在不过分降低画质的情况下压缩文件的大小。如果你已经做到了这一点,那你可以考虑一下如何通过JavaScript来优化图片的下载了,我们将会在下面的篇幅提到这些内容。

+ +

图片占位符

+ +

我们可以通过使用JavaScript有选择的加载图片,而不是把所有的游戏截图都放到 <img> 标签的 src 属性里面,因为那样浏览器会自动下载所有的图片。 js13kPWA示例在图片最终加载之前会将图片的最终路径存放到 data-src 中,在这个阶段,应用会使用图片占位符来代替真正的图片,它体积更小更轻量级(加载也更快,译者注)。

+ +
<img src='data/img/placeholder.png' data-src='data/img/SLUG.jpg' alt='NAME'>
+
+ +

这些图片会在网站构建完HTML主体框架之后通过JavaScript进行加载。图片占位符被缩放到和真正的图片一样大小,所以它会占据同样的空间,并且在真正的图片完成加载后不会导致页面重绘。

+ +

通过JavaScript进行加载

+ +

app.js 这个文件处理 data-src 属性的过程如下所示:

+ +
let imagesToLoad = document.querySelectorAll('img[data-src]');
+const loadImages = (image) => {
+  image.setAttribute('src', image.getAttribute('data-src'));
+  image.onload = () => {
+    image.removeAttribute('data-src');
+  };
+};
+ +

当函数 loadImages 把地址从  data-src 移动到 src 上时,  imagesToLoad 变量包含了所有图片的链接。当每个图片都已经加载完成时,我们会把data-src 属性移除掉,因为这个时候已经没有任何用处了。我们对遍历了所有的图片来加载这些图片:

+ +
imagesToLoad.forEach((img) => {
+  loadImages(img);
+});
+ +

用CSS制造模糊

+ +

为了让整个过程在视觉上更加吸引人,图片占位符的样式用CSS做了模糊处理.

+ +

Screenshot of placeholder images in the js13kPWA app.

+ +

我们在开始时用模糊来渲染图像,因此可以实现一个从模糊到清晰图像的过渡效果:

+ +
article img[data-src] {
+  filter: blur(0.2em);
+}
+
+article img {
+  filter: blur(0em);
+  transition: filter 0.5s;
+}
+ +

这个样式会在半秒钟内移除模糊效果,它会让“加载”效果看起来更好看:

+ +

按需加载

+ +

上面讨论的图片加载机制工作得还不错——它在HTML文档加载完成之后再开始加载图片,并且在加载过程中还提供了一个很漂亮的过度效果。问题是它仍然一次性加载了所有的图片,即使网站加载完成后用户有可能只看前两张或者三张图片。

+ +

这个问题可以用新的 Intersection Observer API 来解决 —— 通过这个api我们可以确保只有当图片出现在可见区域时,它才会被加载。

+ +

Intersection Observer

+ +

这是对上面那个可以正常工作的例子提供的一个渐进增强功能 —— Intersection Observer 只有在用户向下滚动页面并且显示在屏幕上时,才会开始加载目标图片。

+ +

这里有相关的代码展示:

+ +
if('IntersectionObserver' in window) {
+  const observer = new IntersectionObserver((items, observer) => {
+    items.forEach((item) => {
+      if(item.isIntersecting) {
+        loadImages(item.target);
+        observer.unobserve(item.target);
+      }
+    });
+  });
+  imagesToLoad.forEach((img) => {
+    observer.observe(img);
+  });
+} else {
+  imagesToLoad.forEach((img) => {
+    loadImages(img);
+  });
+}
+ +

如果 {{domxref("IntersectionObserver")}}对象被浏览器所支持,app会对它新建一个实例。当一个或多个item(指的是监听的对象,例如一个img,译者注)跟观察者发生交互时(图片出现在视图中时),作为参数传递的函数可以用来处理一些回调事务(例如图片加载,译者注)。我们可以对每一个项目做一个迭代并对它们做出相应的处理——当图片可见时,我们开始加载真正的图片并且停止监听这张图片,因为图片加载完成之后,我们已经没有很必要再知道它的状态了。

+ +

让我们来重申一下我们之前提到的渐进增强 —— 代码这么写的好处在于,不管 Intersection Observer是否被当前浏览器支持,app都能够正常的工作。如果 Intersection Observer不被支持,我们会用上面提到的基础方法来实现图片的加载。

+ +

一些改进

+ +

记住,有很多的方法可以用来优化我们的加载时间,这个示例只探讨了其中的一种方法。你可以尝试让你的app变的更加健壮,通过让它在没有JavaScript的情况下也能工作 —— 通过使用 {{htmlelement("noscript")}} 标签来展示已经分配了最终 src 路径的图片,或者在 <img> 外面套上一个 {{htmlelement("a")}} 标签并指向对应的图片资源,当用户想要想要看的时候他们可以点击图片并访问他们。

+ +

我们并没有这么做因为这个app本身依赖于JavaScript —— 没有JavaScript游戏列表就无法加载,Service Worker相关的代码也将无法执行。

+ +

我们可以重写整个加载过程,让它不止加载图片,而是加载整个列表项,包括详细介绍和链接。工作起来它像一个无限滚动的页面——当用户往下滚动的时候开始加载新的项目。通过这个方法HTML页面体积会达到最小,加载时间可以更短,我们也可以从中获取到更大的性能优势。

+ +

结论

+ +

初始化时加载更少的文件,分拆成更小的模块,使用占位符以及按需加载更多的内容 —— 这会让我们获得更短的首次加载时间,它既能让app开发者受益,也能给用户提供更加丝滑的体验。

+ +

记住关于渐进增强的内容 —— 不管在任何硬件或平台都提供一个可用的产品,但在现代浏览器上面确保能提供更好的用户体验。

+ +

最后的思考

+ +

这就是这个系列的所有内容了 —— 我们通过  js13kPWA 示例应用的源码 学习了渐进式web 应用的的用法,包括了PWA介绍, PWA 结构, 通过Service Workers让PWA离线工作, 让PWA易于安装,以及最后的通知功能。在Service Worker Cookbook的帮助下我们还解释了推送的原理。而在本篇文章中,我们探讨了渐进式加载的概念,包括一个使用了 Intersection Observer API的有趣例子。

+ +

请随意试验这些代码,通过使用PWA的特性来让你现有的应用更加健壮,或者自己创建一些全新的东西。相对于常规的web应用,PWA存在巨大的优势。

+ +

{{PreviousMenu("Web/Apps/Progressive/Re-engageable_Notifications_Push", "Web/Apps/Progressive")}}

+ +

{{QuickLinksWithSubpages("/en-US/docs/Web/Progressive_web_apps/")}}

diff --git a/files/zh-cn/web/progressive_web_apps/network_independent/index.html b/files/zh-cn/web/progressive_web_apps/network_independent/index.html deleted file mode 100644 index 4b8b532173..0000000000 --- a/files/zh-cn/web/progressive_web_apps/network_independent/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: 网络独立 -slug: Web/Progressive_web_apps/Network_independent -tags: - - Application Shell - - IndexedDB - - PWA - - Progressive web apps - - Service Workers - - Web Storage - - localStorage -translation_of: Web/Progressive_web_apps -translation_of_original: Web/Progressive_web_apps/Network_independent ---- -
-
当网络不可靠,甚至不存在时,现代网络应用程序仍可以工作。没有更多的空白连接错误页面或恐龙穿过沙漠。除了离线高速缓存和服务工作者之外,UI和内容之间的一个明确的分隔可让您存储应用程序的数据和核心资产,以备将来使用。
- -
-
- -

The basic ideas behind network independence are to be able to:

- - - -

核心指南

- -
-
Using service workers
-
A simple guide for those new to the Service Worker API.
-
Using IndexedDB
-
The basics of IndexedDB, explained in detail.
-
Using the Web Storage API
-
The Web storage API made simple.
-
Instant Loading Web Apps with An Application Shell Architecture
-
A guide to using the App Shell coding pattern to create apps that load quickly.
-
- -

技术

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
技术描述支持概览最新规范
Service workersJavaScript running in a special worker context that is run by the browser under certain circumstances such as fetch or push events. These allow the service worker to intercept responses and customise them in any way you want, for example caching assets for offline use before they are served.Experimental: Chrome and Firefox (more detail){{SpecName('Service Workers')}}
IndexedDBA transactional database system that allows complex client-side data storage to be controlled via JavaScript.Widespread across modern browsers (more detail){{SpecName('IndexedDB')}}
Web StorageA simple API for storing name-value pairs on the client-side.Widespread (more detail){{SpecName('Web Storage')}}
- -

工具

- -
-
localForage
-
A nice simple JavaScript library for making client-side data storage really simple; it uses IndexedDB by default, and falls back to Web SQL/Web Storage if necessary.
-
ServiceWorkerWare
-
An Express-like microframework for easy Service Worker development.
-
oghliner
-
Not only a template but a tool for deploying Offline Web Apps to GitHub Pages.
-
sw-precache
-
A node module to generate service worker code that will precache specific resources.
-
upup
-
A tiny script that makes sure your site is always there for your users.
-
- -

参见

- -
-
The service worker cookbook
-
A series of excellent service worker recipes, showing how to implement an offline app, but also much more.
-
diff --git a/files/zh-cn/web/progressive_web_apps/re-engageable/index.html b/files/zh-cn/web/progressive_web_apps/re-engageable/index.html deleted file mode 100644 index 0ff507d2e6..0000000000 --- a/files/zh-cn/web/progressive_web_apps/re-engageable/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Re-engageable -slug: Web/Progressive_web_apps/Re-engageable -tags: - - Modern web apps - - Notifications API - - Progressive web apps - - Push API - - Service Workers -translation_of: Web/Progressive_web_apps -translation_of_original: Web/Progressive_web_apps/Re-engageable ---- -
-
原生平台一个主要优势是,用户可以轻松通过更新或加载新内容,即使用户没有正在查看应用程序或者使用他们的设备。现在的Web应用程序现在也可以使用Web Push API等技术实现这样的功能。
- -
-
- -

核心指南

- -
-
Using service workers
-
A simple guide for those new to the Service Worker API.
-
Using the Push API
-
Learn the essentials behind the Web Push API.
-
Using the Notifications API
-
Web notifications in a nutshell.
-
- -

技术

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
技术描述浏览器支持最新规范
Service workersJavaScript running in a special worker context that is run by the browser under certain circumstances such as fetch or push events. These allow the service worker to intercept responses and customise them in any way you want, for example caching assets for offline use before they are served.Experimental: Chrome and Firefox (more detail){{SpecName('Service Workers')}}
Push APIWhen subscribed to, the push service provides an endpoint that can be used by a server to send a push message to a web app under the control of a particular service worker.Experimental: chrome and Firefox (more detail){{SpecName("Push API")}}
Notifications APIFires system notifications directly from web applications.Widespreadin modern browsers (more detail){{SpecName('Web Notifications')}}
- -

工具

- -
-
ServiceWorkerWare
-
An Express-like microframework for easy Service Worker development.
-
oghliner
-
Not only a template but a tool for deploying Offline Web Apps to GitHub Pages.
-
sw-precache
-
A node module to generate service worker code that will precache specific resources.
-
- -

参见

- -
-
The service worker cookbook
-
A series of excellent service worker recipes, showing how to implement an offline app, but also much more.
-
diff --git a/files/zh-cn/web/progressive_web_apps/responsive/index.html b/files/zh-cn/web/progressive_web_apps/responsive/index.html deleted file mode 100644 index 3177fc1c29..0000000000 --- a/files/zh-cn/web/progressive_web_apps/responsive/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Responsive design -slug: Web/Progressive_web_apps/Responsive -tags: - - Media Queries - - PWA - - Progressive web apps - - Responsive web design - - viewport -translation_of: Web/Progressive_web_apps/Responsive/responsive_design_building_blocks -translation_of_original: Web/Progressive_web_apps/Responsive ---- -
-
响应式Web应用使用媒体查询和viewport等技术,以确保它们的页面适配任何设备,比如:桌面、移动手机、平板,或者其他新的设备。
- -
-
- -

核心指南

- -
-
The building blocks of responsive design
-
Learn the basics of responsive design, an essential topic for modern app layout.
-
Mobile first
-
Often when creating responsive application layouts, it makes sense to create the mobile layout as the default, and build wider layouts on top.
-
- -

技术

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TechnologyDescriptionSupport summaryLatest spec
Media queriesDefines expressions allowing styling to be selectively applied to content depending on viewport size, resolution, orientation, etc.Widespread across modern browsers (more detail)Media Queries Level 4
@viewport/viewport meta tagControls viewport settings, primarily on mobile devices.@viewport: Experimental (more detail)
- Viewport meta tag: Widespread across modern mobile devices
CSS Device Adaptation Module Level 1
FlexboxA very useful CSS feature for creating flexible, responsive layouts.Widespread across modern browsers (more detail)CSS Flexible Box Layout Module Level 1
- -

工具

- -
-
Modernizr
-
A feature detection library for applying different CSS and JS to your page depending on whether certain CSS/JS features are supported.
-
css3-mediaqueries-js
-
A JavaScript polyfill to add Media Query support to old versions of IE (5+.)
-
- -

参见

- -
-
Graphics for responsive sites
-
Ideas to keep in mind when designing graphics for responsive sites and applications.
-
Responsive navigation patterns
-
How do you make a UI that looks and works as great on a smartphone as it does on the desktop? Learn how to design UIs that change to fit your user's screen.
-
diff --git a/files/zh-cn/web/progressive_web_apps/responsive/media_types/index.html b/files/zh-cn/web/progressive_web_apps/responsive/media_types/index.html new file mode 100644 index 0000000000..ef181eedcc --- /dev/null +++ b/files/zh-cn/web/progressive_web_apps/responsive/media_types/index.html @@ -0,0 +1,391 @@ +--- +title: 媒体 +slug: Web/Guide/CSS/Getting_started/Media +translation_of: Web/Progressive_web_apps/Responsive/Media_types +--- +

{{CSSTutorialTOC}} {{previousPage("/zh-CN/docs/Web/Guide/CSS/Getting_Started/Tables", "表格")}}

+ +

本章节是 CSS入门教程 指南的第14章也是最后一部分。 这本指南主要描述了用来展示文档的CSS的属性及其值,本章节依旧着眼于这个目标,同时也会介绍CSS样式表的结构。

+ +

信息: Media

+ +

CSS的作用是将网页文档以更友好的展现方式呈现给用户。

+ +

例如,假设你现在正用一台显示设备来阅读这篇文章,同时你也想把它投影到屏幕上,或者打印出来,而显示设备、屏幕投影和打印等这些媒介都有自己的特点,CSS就是为文档提供在不同媒介上展示的适配方法。

+ +

CSS通过使用{{CSSXref("@media")}} 的格式来对特定的媒介指定适配规则。

+ +
+
示例
+ +

我们的站点上有一个导航区域允许用户浏览。

+ +

在标签语言中,导航区域父元素的id是 nav-area.(在 {{HTMLVersionInline(5)}}中, 可以使用 {{HTMLElement("nav")}} 元素代替带有id属性的 {{HTMLElement("div")}}。)

+ +

为了网页在被打印的时候去掉无用的信息,我们在样式表中加一条适配规则,使导航区域在打印时是被隐藏起来的:

+ +
@media print {
+  #nav-area {display: none;}
+  }
+
+
+ +

一些常见的媒介类型:

+ + + + + + + + + + + + + + + + + + + + +
screen彩色计算机显示
print打印(分页式媒体)
projection投影
all所有媒体 (默认)
+ +
+
更多
+ +

一些其他指定媒介类型的规则。

+ +

类型可以在样式表通过link方式加到文档时被指定,这是文档的标签语言允许的 。例如,在HTML中,你可以通过在 LINK 标签上添加media属性来指定媒介类型。

+ +

在CSS中,你可以在样式表开头使用 {{CSSXref("@import")}} 一个url来引入另外的样式表,同时指定其媒介类型。

+ +

根据这些知识,你可以区分在不同的文件中定义不同媒介的样式规则。有时这也是结构化样式表的好方法。

+ +

想获取媒介类型更多细节,请参考CSS规范中的 Media 部分。

+ +

接下来将介绍更多 {{cssxref("display")}} 属性的例子: XML data.

+
+ +

打印

+ +

CSS有一些特性能够支持打印和分页媒体。

+ +

 {{cssxref("@page")}} 规则能够设置页间距,对于双面打印,还可以分开设置 @page:left 和 @page:right。

+ +

对于打印媒介,可以使用适当的长度单位,像是英寸(in)、点(1pt = 1/72 inch)、厘米(cm)还有毫米(mm)。这等同于使用em来配合字体大小和百分比。

+ +

可以通过使用 {{cssxref("page-break-before")}}, {{cssxref("page-break-after")}} 和 {{cssxref("page-break-inside")}} 属性来控制文档内容的分页边界。

+ +
+
示例
+ +

这个规则把四个方向的页边距都设置为1 inch:

+ +
@page {margin: 1in;} 
+ +

这个规则确保每个H1元素都从新的一页开始:

+ +
h1 {page-break-before: always;}
+
+
+ +
+
更多细节
+ +

想获取更多细节,请参考CSS规范中的 Paged media 部分。

+ +

像CSS的其他特性一样,打印也依赖于你的浏览器及其设置。例如,在打印的时候Mozilla浏览器支持默认的间距,页眉和页脚。而当其他用户打印你的文档时,你无法预知他会使用的什么样的浏览器和设置,因此你也不能完全控制打印情况。

+
+ +

用户界面

+ +

CSS有一些特殊的属性能够支持设备的用户界面,像电脑显示器。这使得文档的展示随着用户界面的情况而动态地变化。

+ +

并没有针对用户界面设备的特殊媒介类型。

+ +

下面有五种特殊的选择器:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SelectorSelects
E{{cssxref(":hover")}}当鼠标悬浮任何E元素上
E{{cssxref(":focus")}}当元素获得键盘焦点
E{{cssxref(":active")}}当元素是当前的活动元素
E{{cssxref(":link")}}当元素超链接到一个url但是用户还没有访问过
E{{cssxref(":visited")}}当元素超链接到一个url但是用户已经访问过
+ +
+

注意: 在 {{gecko("2.0")}} 中可获得的 :visited 选择器信息是有限的。更过细节请参照 Privacy and the :visited selector 。

+
+ +

 {{cssxref("cursor")}} 属性指定鼠标的形状:一些常见的形状如下表所示。把你的鼠标放在列表的选项上来看浏览器中实际显示的鼠标形状:

+ + + + + + + + + + + + + + + + + + + + + + + + +
SelectorSelects
pointer指示超链接
wait表明程序无法接受输入
progress表明程序正在运行,但是仍可以接受输入
default默认(通常是箭头)
+ +

 {{cssxref("outline")}} 属性通过创建轮廓来表明获得键盘焦点。只有在父元素使用 relative, fixed or absolute 时才有效。你可以为任何父元素指定 position: relative;因为它不会产生移动。
+ 它的作用相当于 {{cssxref("border")}} 属性,但与其不同的是它不能指明个别方向。

+ +

一些其他的用户界面特性通常会通过属性来应用。例如,禁用或者只读的元素可以设置 disabled 属性和 readonly 属性。选择器可以通过方括: {{mediawiki.external('disabled')}} 或者 {{mediawiki.external('readonly')}}来指定这些属性。

+ +
+
示例
+ +

这些规则规定了按钮在用户使用时动态变化的样式:

+ +
.green-button {
+  background-color:#cec;
+  color:#black;
+  border:2px outset #cec;
+  }
+
+.green-button[disabled] {
+  background-color:#cdc;
+  color:#777;
+  }
+
+.green-button:active {
+  border-style: inset;
+  } 
+ +

这个wiki不支持页面上的用户界面,所以这些按钮不能点击。下面用一些静态图片来举例说明:

+ + + + + + + +
+ + + + + + + + + + + + + + + + +
Click MeClick MeClick Me
 
disablednormalactive
+
+ +

当一个功能性按钮初始化的时候,它的周围会围绕着一条黑色的轮廓。当它获取键盘焦点时,从表面上看有一条虚线轮廓。同时当鼠标悬浮在它上面时也有一些悬浮效果。

+
+ +
+
更多
+ +

获取更多关于CSS用户界面的信息,请参考CSS规范中的 User interface 部分。

+ +

本文的第二部分列举了Mozilla的用户界面标签语言的例子,XUL。

+
+ +

实践: 打印文档

+ +
    +
  1. 创建一个新的HTML文档, doc4.html. 把下面的HTML代码粘贴过去: + +
    <!DOCTYPE html>
    +<html>
    +  <head>
    +    <title>Print sample</title>
    +    <link rel="stylesheet" href="style4.css">
    +  </head>
    +  <body>
    +    <h1>Section A</h1>
    +    <p>This is the first section...</p>
    +    <h1>Section B</h1>
    +    <p>This is the second section...</p>
    +    <div id="print-head">
    +      Heading for paged media
    +    </div>
    +    <div id="print-foot">
    +      Page:
    +    </div>
    +</body>
    +</html>
    +
    +
  2. +
  3. 创建一个新的样式表, style4.css. 把下面的HTML代码粘贴过去: +
    /*** Print sample ***/
    +
    +/* defaults  for screen */
    +#print-head,
    +#print-foot {
    +  display: none;
    +  }
    +
    +/* print only */
    +@media print {
    +
    +h1 {
    +  page-break-before: always;
    +  padding-top: 2em;
    +  }
    +
    +h1:first-child {
    +  page-break-before: avoid;
    +  counter-reset: page;
    +  }
    +
    +#print-head {
    +  display: block;
    +  position: fixed;
    +  top: 0pt;
    +  left:0pt;
    +  right: 0pt;
    +
    +  font-size: 200%;
    +  text-align: center;
    +  }
    +
    +#print-foot {
    +  display: block;
    +  position: fixed;
    +  bottom: 0pt;
    +  right: 0pt;
    +
    +  font-size: 200%;
    +  }
    +
    +#print-foot:after {
    +  content: counter(page);
    +  counter-increment: page;
    +  }
    +
    +} /* end print only */
    +
    +
  4. +
  5. 在浏览器中查看文档,你会看到它使用的是默认样式。
  6. +
  7. 打印(或者打印预览)文档;样式表的适配规则开始起作用,同时会显示每个页面的页眉和页脚,如果浏览器支持记数器,页码也会被显示出来。 + + + + + + + +
    + + + + + + +
    + + + + + + +
    +
    Heading for paged media
    + +
    Section A
    + +
    This is the first section...
    + +
    Page: 1
    +
    +
    +
    + + + + + + +
    + + + + + + +
    +
    Heading for paged media
    + +
    Section B
    + +
    This is the second section...
    + +
    Page: 2
    +
    +
    +
    +
  8. +
+ + + + + + + + +
挑战
把指定打印样式的规则转移到单独的CSS文件。 +

学习 {{CSSXref("@import")}} 了解如何将新的指定打印 CSS 文件引用到 style4.css 样式表里去。

+ +

当鼠标放在标题时,改变颜色为蓝色。

+
+ +

查看这些挑战的解决方案。

+ +

接下来?

+ +

如果你还是很难理解这个章节,或者你对它有一些意见或者建议,请在 讨论区 中不吝赐教。

+ +

目前,本文所有的样式规则都可以在文件里面规定。这些规则及其值均是固定的。下面的篇章将会描述该如何使用程序语言 JavaScript 来动态地改变规则。

diff --git "a/files/zh-cn/web/progressive_web_apps/\344\274\230\345\212\277/index.html" "b/files/zh-cn/web/progressive_web_apps/\344\274\230\345\212\277/index.html" deleted file mode 100644 index 809b1edb38..0000000000 --- "a/files/zh-cn/web/progressive_web_apps/\344\274\230\345\212\277/index.html" +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: 渐进式webApp优势 -slug: Web/Progressive_web_apps/优势 -translation_of: Web/Progressive_web_apps/Introduction#Advantages_of_web_applications -translation_of_original: Web/Progressive_web_apps/Advantages ---- -

以下是渐进式webApp所有的优势清单

- -

Discoverable

- -

The eventual aim is that web apps should have better representation in search engines, be easier to expose, catalog and rank, and have metadata usable by browsers to give them special capabilities.

- -

Some of the capabilities have already been enabled on certain web-based platforms by proprietary technologies like Open Graph, which provides a format for specifying similar metadata in the HTML <head> using meta tags.

- -

The relevant web standard here is the Web app manifest, which defines features of an app such as name, icon, splash screen, and theme colors in a JSON-formatted manifest file. This is for use in contexts such as app listings and device home screens.

- - - -

Installable

- -

A core part of the apps experience is for users to have app icons on their home screen, and be able to tap to open apps into their own native container that feels nicely integrated with the underlying platform.

- -

Modern web apps can have this native app feel via properties set inside the Web app manifest, and via a feature available in modern smartphone browsers called Add to home screen.

- -

Linkable

- -

One of the most powerful features of the Web is to be able to link to an app at a specific URL — no app store needed, no complex installation process. This is how it has always been.

- -

Network independent

- -

Modern web apps can work when the network is unreliable, or even non-existent. The basic ideas behind network independence are to be able to:

- - - -

This is achieved by a combination of technologies — Service Workers to control page requests (for example storing them offline), the Cache API for storing responses to network requests offline (very useful for storing site assets), and client-side data storage technologies such as Web Storage and IndexedDB to store application data offline.

- -

Progressive

- -

Modern web apps can be developed to provide a super cool experience to fully capable browsers, and an acceptable (although not quite as shiny) experience to less capable browsers. We've been doing this for years with best practices such as progressive enhancement.

- -

Re-engageable

- -

One major advantage of native platforms is the ease with which users can be re-engaged by updates and new content, even when they aren't looking at the app or using their devices. Modern web apps can now do this too, using new technologies such as Service Workers for controlling pages, the Web Push API for sending updates straight from server to app via a service worker, and the Notifications API for generating system notifications to help engage users when they're not in the browser.

- -

Responsive

- -

Responsive web apps use technologies like media queries and viewport to make sure that their UIs will fit any form factor: desktop, mobile, tablet, or whatever comes next.

- -

Safe

- -

The web platform provides a secure delivery mechanism that prevents snooping and ensures content hasn’t been tampered with — as long as you take advantage of HTTPS and develop your apps with security in mind. In addition, you can verify the true nature of a PWA by confirming that it is at the correct URL, whereas apps in apps stores can often look like one thing, but be another (example).

- -

 

diff --git "a/files/zh-cn/web/progressive_web_apps/\345\212\240\350\275\275/index.html" "b/files/zh-cn/web/progressive_web_apps/\345\212\240\350\275\275/index.html" deleted file mode 100644 index 7f45a3c278..0000000000 --- "a/files/zh-cn/web/progressive_web_apps/\345\212\240\350\275\275/index.html" +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: 渐进式加载 -slug: Web/Progressive_web_apps/加载 -tags: - - PWA - - 渐进式加载 -translation_of: Web/Progressive_web_apps/Loading ---- -
{{PreviousMenu("Web/Apps/Progressive/Re-engageable_Notifications_Push", "Web/Apps/Progressive")}}
- -

在前面的文章我们介绍了很多api,例如:Service Workers, Web Manifests, Notifications and Push,它让我们的示例应用 js13kPWA 成为一个渐进式web应用。在这篇文章里我们将会走得更远,我们会使用资源渐进式加载来提高整个应用的性能。

- -

首次有效渲染

- -

尽快把有效的信息输送给用户是一件非常重要的事情 —— 等待页面加载的时间越长,用户在页面加载完成之前离开的概率就越大。为了达到这个目的,网页加载完成前,我们应该用占位符在最终资源将会加载的地方展示最起码的视图骨架。

- -

这个功能可以用渐进式加载来实现 —— 它也被称为 懒加载。它的做法是延迟加载尽可能多的资源(HTML, CSS, JavaScript),只有在用户第一次使用到它的时候,它才会被立刻加载。

- -

打包还是拆分

- -

大部分的用户不会用到一个网站的所有页面,但我们通常的做法却是把我们所有的功能都打包进一个很大的文件里面。一个 bundle.js 文件的大小可能会有几个M,一个打包后的style.css 会包含一切东西,从CSS结构定义到各个版本的网站的样式:移动端,平板,桌面,打印等等。

- -

通常来说只加载一个打包后大的文件会比加载很多个小文件要快一些,但如果用户并不是一开始就需要所有的资源,我们就可以首先加载那些关键的资源,其他的等到我们需要的时候,我们再去加载它。

- -

导致页面阻塞的资源(Render-blocking resources)

- -

将所有文件打包是一种不好的做法,因为浏览器把计算结果渲染到屏幕之前,需要先把HTML,CSS和JavaScript下载下来。在页面被打开到页面加载完成的这段时间里,用户将会看到一个空白的页面,这无疑是一个非常糟糕的体验。

- -

为了解决这个问题,举个例子,我们可以在script标签上面加上一个 defer

- -
<script src="app.js" defer></script>
-
- -

他们会等到文档解析完成之后再开始下载和执行,所以他们不会阻塞HTML页面的渲染。我们还可以拆分css文件并给它们加上media属性:

- -
<link rel="stylesheet" href="style.css">
-<link rel="stylesheet" href="print.css" media="print">
-
- -

 这种做法告诉浏览器只有在条件满足的情况下才加载这些资源(例如指定了print,则在打印环境下才会加载这些资源,译者注)。

- -

在我们这个js13kPWA应用里面,由于CSS非常的简单,因此所有样式都被放到一个文件里面,并没有具体的规则来指导它如何加载css。但我们可以做得更好,例如把 style.css 里面的所有内容移动到一个 <style> 标签里面,并把它放到 index.html  的 <head> 的里面。这样做可以进一步提高应用的性能,但为了使代码更具可读性,我们并没有选择这么做。

- -

图片

- -

除了JavaScript和CSS,网站通常还会包含大量的图片。当你把{{htmlelement("img")}}元素添加到网站里面时,对应的所有图片资源都会在页面初始化时被下载下来。在网站就绪之前下载几个兆的图片资源是一种比较常见的状况,但它会再次给人一种性能不好的印象。我们并不需要在一打开网站的时候就以最高的画质呈现所有的图片。

- -

这是可以优化的。首先,你可以使用类似TinyPNG这类工具或者服务,它可以在不过分降低画质的情况下压缩文件的大小。如果你已经做到了这一点,那你可以考虑一下如何通过JavaScript来优化图片的下载了,我们将会在下面的篇幅提到这些内容。

- -

图片占位符

- -

我们可以通过使用JavaScript有选择的加载图片,而不是把所有的游戏截图都放到 <img> 标签的 src 属性里面,因为那样浏览器会自动下载所有的图片。 js13kPWA示例在图片最终加载之前会将图片的最终路径存放到 data-src 中,在这个阶段,应用会使用图片占位符来代替真正的图片,它体积更小更轻量级(加载也更快,译者注)。

- -
<img src='data/img/placeholder.png' data-src='data/img/SLUG.jpg' alt='NAME'>
-
- -

这些图片会在网站构建完HTML主体框架之后通过JavaScript进行加载。图片占位符被缩放到和真正的图片一样大小,所以它会占据同样的空间,并且在真正的图片完成加载后不会导致页面重绘。

- -

通过JavaScript进行加载

- -

app.js 这个文件处理 data-src 属性的过程如下所示:

- -
let imagesToLoad = document.querySelectorAll('img[data-src]');
-const loadImages = (image) => {
-  image.setAttribute('src', image.getAttribute('data-src'));
-  image.onload = () => {
-    image.removeAttribute('data-src');
-  };
-};
- -

当函数 loadImages 把地址从  data-src 移动到 src 上时,  imagesToLoad 变量包含了所有图片的链接。当每个图片都已经加载完成时,我们会把data-src 属性移除掉,因为这个时候已经没有任何用处了。我们对遍历了所有的图片来加载这些图片:

- -
imagesToLoad.forEach((img) => {
-  loadImages(img);
-});
- -

用CSS制造模糊

- -

为了让整个过程在视觉上更加吸引人,图片占位符的样式用CSS做了模糊处理.

- -

Screenshot of placeholder images in the js13kPWA app.

- -

我们在开始时用模糊来渲染图像,因此可以实现一个从模糊到清晰图像的过渡效果:

- -
article img[data-src] {
-  filter: blur(0.2em);
-}
-
-article img {
-  filter: blur(0em);
-  transition: filter 0.5s;
-}
- -

这个样式会在半秒钟内移除模糊效果,它会让“加载”效果看起来更好看:

- -

按需加载

- -

上面讨论的图片加载机制工作得还不错——它在HTML文档加载完成之后再开始加载图片,并且在加载过程中还提供了一个很漂亮的过度效果。问题是它仍然一次性加载了所有的图片,即使网站加载完成后用户有可能只看前两张或者三张图片。

- -

这个问题可以用新的 Intersection Observer API 来解决 —— 通过这个api我们可以确保只有当图片出现在可见区域时,它才会被加载。

- -

Intersection Observer

- -

这是对上面那个可以正常工作的例子提供的一个渐进增强功能 —— Intersection Observer 只有在用户向下滚动页面并且显示在屏幕上时,才会开始加载目标图片。

- -

这里有相关的代码展示:

- -
if('IntersectionObserver' in window) {
-  const observer = new IntersectionObserver((items, observer) => {
-    items.forEach((item) => {
-      if(item.isIntersecting) {
-        loadImages(item.target);
-        observer.unobserve(item.target);
-      }
-    });
-  });
-  imagesToLoad.forEach((img) => {
-    observer.observe(img);
-  });
-} else {
-  imagesToLoad.forEach((img) => {
-    loadImages(img);
-  });
-}
- -

如果 {{domxref("IntersectionObserver")}}对象被浏览器所支持,app会对它新建一个实例。当一个或多个item(指的是监听的对象,例如一个img,译者注)跟观察者发生交互时(图片出现在视图中时),作为参数传递的函数可以用来处理一些回调事务(例如图片加载,译者注)。我们可以对每一个项目做一个迭代并对它们做出相应的处理——当图片可见时,我们开始加载真正的图片并且停止监听这张图片,因为图片加载完成之后,我们已经没有很必要再知道它的状态了。

- -

让我们来重申一下我们之前提到的渐进增强 —— 代码这么写的好处在于,不管 Intersection Observer是否被当前浏览器支持,app都能够正常的工作。如果 Intersection Observer不被支持,我们会用上面提到的基础方法来实现图片的加载。

- -

一些改进

- -

记住,有很多的方法可以用来优化我们的加载时间,这个示例只探讨了其中的一种方法。你可以尝试让你的app变的更加健壮,通过让它在没有JavaScript的情况下也能工作 —— 通过使用 {{htmlelement("noscript")}} 标签来展示已经分配了最终 src 路径的图片,或者在 <img> 外面套上一个 {{htmlelement("a")}} 标签并指向对应的图片资源,当用户想要想要看的时候他们可以点击图片并访问他们。

- -

我们并没有这么做因为这个app本身依赖于JavaScript —— 没有JavaScript游戏列表就无法加载,Service Worker相关的代码也将无法执行。

- -

我们可以重写整个加载过程,让它不止加载图片,而是加载整个列表项,包括详细介绍和链接。工作起来它像一个无限滚动的页面——当用户往下滚动的时候开始加载新的项目。通过这个方法HTML页面体积会达到最小,加载时间可以更短,我们也可以从中获取到更大的性能优势。

- -

结论

- -

初始化时加载更少的文件,分拆成更小的模块,使用占位符以及按需加载更多的内容 —— 这会让我们获得更短的首次加载时间,它既能让app开发者受益,也能给用户提供更加丝滑的体验。

- -

记住关于渐进增强的内容 —— 不管在任何硬件或平台都提供一个可用的产品,但在现代浏览器上面确保能提供更好的用户体验。

- -

最后的思考

- -

这就是这个系列的所有内容了 —— 我们通过  js13kPWA 示例应用的源码 学习了渐进式web 应用的的用法,包括了PWA介绍, PWA 结构, 通过Service Workers让PWA离线工作, 让PWA易于安装,以及最后的通知功能。在Service Worker Cookbook的帮助下我们还解释了推送的原理。而在本篇文章中,我们探讨了渐进式加载的概念,包括一个使用了 Intersection Observer API的有趣例子。

- -

请随意试验这些代码,通过使用PWA的特性来让你现有的应用更加健壮,或者自己创建一些全新的东西。相对于常规的web应用,PWA存在巨大的优势。

- -

{{PreviousMenu("Web/Apps/Progressive/Re-engageable_Notifications_Push", "Web/Apps/Progressive")}}

- -

{{QuickLinksWithSubpages("/en-US/docs/Web/Progressive_web_apps/")}}

diff --git "a/files/zh-cn/web/progressive_web_apps/\346\267\273\345\212\240\345\210\260\344\270\273\345\261\217\345\271\225/index.html" "b/files/zh-cn/web/progressive_web_apps/\346\267\273\345\212\240\345\210\260\344\270\273\345\261\217\345\271\225/index.html" deleted file mode 100644 index a0915ea9d2..0000000000 --- "a/files/zh-cn/web/progressive_web_apps/\346\267\273\345\212\240\345\210\260\344\270\273\345\261\217\345\271\225/index.html" +++ /dev/null @@ -1,218 +0,0 @@ ---- -title: 添加到主屏幕 -slug: Web/Progressive_web_apps/添加到主屏幕 -tags: - - PWA - - 图标 - - 服务进程 - - 添加到主屏幕 - - 清单 - - 渐进式Web应用 -translation_of: Web/Progressive_web_apps/Add_to_home_screen ---- -

添加到主屏幕(A2HS)添加到主屏幕(简称A2HS)是现代智能手机浏览器中的一项功能,使开发人员可以轻松便捷地将自己喜欢的Web应用程序(或网站)的快捷方式添加到主屏幕中,以便他们随后可以通过单点访问它。本指南说明了A2HS的使用方式,以及作为开发人员要使您的用户利用A2HS所需做的事情。

- -

为什么选择A2HS?

- -

A2HS被认为是渐进式Web应用程序哲学的一部分—为Web应用程序提供与原生应用程序相同的用户体验优势,因此它们可以在当今的生态系统战争中竞争。这部分是通过访问主屏幕上的应用程序图标来访问应用程序,然后将其整齐地显示在自己的窗口中的简单手势。A2HS使这成为可能。

- -

哪些浏览器支持A2HS?

- -

Mobile Chrome / Android Webview 从31版开始支持A2HS,Opera for Android从32版开始支持,Firefox for Android从58版开始支持。

- -

如何使用?

- -

我们已经编写了一个非常简单的示例网站(观看我们的在线演示,并查看源代码),该网站虽然功能不多,但是开发时使用了必要的代码,也可以将其添加到主屏幕中,并且service worker使其可以脱机使用。这个示例展示了一系列的狐狸图片。

- -

如果您有适用于Android的Firefox,使用它导航到我们的示例:https://mdn.github.io/pwa-examples/a2hs/。你将会看到狐狸图片,但更重要的是,你将会看到一个带有加号(+)的“主页”图标—这是为具有必要功能的任何站点显示的“添加到主屏幕”图标。

- -

- -

点击此按钮将显示一个确认横幅—按下大“+ 添加到主屏幕”按钮即可完成操作,将应用添加到主屏幕。(注意:在Android 8及更高版本中,将首先显示系统级的“添加到主屏幕”权限对话框。)

- -

- -

如果您可以使用Mobile Chrome,则体验会略有不同;加载我们的网站后,您会看到一个弹出安装横幅,询问您是否要将此应用添加到主屏幕。

- -

- -
-

注意:您可以在“Web App安装横幅”一文中找到有关Chrome安装横幅的更多信息。

-
- -

如果您选择不将其添加到主屏幕,则可以稍后使用Chrome主菜单中的添加到主屏幕图标添加。

- -

无论使用哪种浏览器,当您选择将应用程序添加到主屏幕时,您都会看到它与短标题一起出现,就像原生应用程序一样。

- -

- -

点按此图标可以将其打开,但是作为全屏应用程序,您将不再看到其周围的浏览器用户界面。

- -

如何使应用程序支持A2HS?

- -

要将您的应用添加到主屏幕,它需要满足以下条件:

- - - -

Manifest

- -

web manifest 以标准JSON格式编写,应放置在应用程序目录中的某个位置(最好是在根目录中),名称为somefilename.webmanifest(我们选择 manifest.webmanifest)。它包含多个字段,这些字段定义有关Web应用程序及其行为的某些信息。

- -
-

注意:.webmanifest扩展名是在规范的“媒体类型注册”部分中指定的,但通常浏览器将支持带有其他适当扩展名的清单,例如:.json。

-
- -

A2HS所需的字段如下:

- - - -

我们的示例应用程序的manifest如下所示:

- -
{
-  "background_color": "purple",
-  "description": "Shows random fox pictures. Hey, at least it isn't cats.",
-  "display": "fullscreen",
-  "icons": [
-    {
-      "src": "icon/fox-icon.png",
-      "sizes": "192x192",
-      "type": "image/png"
-    }
-  ],
-  "name": "Awesome fox pictures",
-  "short_name": "Foxes",
-  "start_url": "/pwa-examples/a2hs/index.html"
-}
- -

合适的图标

- -

如以上manifest所示,我们包括一个192 x 192像素的图标,供我们的应用使用。您可以根据需要添加更多尺寸;Android将为每个不同的用例选择最合适的尺寸。您还可以决定添加不同类型的图标,以便设备可以使用他们能够使用的最佳图标(例如,Chrome已经支持WebP格式).

- -

请注意,每个图标对象中的 type 成员都指定了该图标的mimetype,因此浏览器可以快速读取该图标的类型,然后将其忽略,并在不支持该图标时采用其他图标。

- -

在设计图标方面,您应该遵循与任何Android图标相同的最佳做法(请参阅Android图标设计指南)。

- -

将HTML链接到manifest

- -

要完成manifest的设置,您需要从应用程序主页的 HTML 中引用它:

- -
<link rel="manifest" href="manifest.webmanifest">
- -

一旦支持 manifest,支持 A2HS 的浏览器就会知道在哪里查找它。

- -

A2HS没有给你什么?

- -

请记住,将应用程序添加到主屏幕时,它只会使该应用程序易于访问—不会将应用程序的资产和数据下载到您的设备上,也不会使该应用程序脱机使用或类似的操作。 为了使你的应用离线运行,你必须使用Service Worker API来离线存储资源,如果需要,还可以使用 Web storage 或 IndexedDB 来存储其数据。

- -

在示例应用程序中,我们仅使用了一个service worker来存储所有必需的文件。service worker使用index.js 文件中的最终的代码块在网站上注册。然后,我们使用 Cache API 缓存网站的所有资产,并使用 sw.js 文件中的代码从缓存而不是网络中为它们提供服务。

- -

桌面上的A2HS

- -

虽然最初旨在改善移动操作系统上的用户体验,但人们也提出了使PWA也可以安装在桌面平台上的趋势。

- -
-

注意:在撰写本文时,仅在较新版本的Chrome(在Windows中默认情况下,在macOS上的#enable-desktop-pwas标志开启后)中支持以下功能。

-
- -

添加安装按钮

- -

为了使PWA可在桌面上安装,我们首先在文档中添加了一个按钮,以允许用户进行安装—桌面应用程序不会自动提供此按钮,并且需要通过用户手势来触发安装:

- -
<button class="add-button">Add to home screen</button>
- -

然后,我们给它一些简单的样式:

- -
.add-button {
-  position: absolute;
-  top: 1px;
-  left: 1px;
-}
- -

用于处理安装的JavaScript

- -

index.js文件的底部,我们添加了一些JavaScript来处理安装。首先,我们声明一个deferredPrompt变量(我们将在后面解释),获得对安装按钮的引用,并初始设置为display: none

- -
let deferredPrompt;
-const addBtn = document.querySelector('.add-button');
-addBtn.style.display = 'none';
- -

我们最初隐藏该按钮是因为PWA必须遵循A2HS标准才能安装。发生这种情况时,支持的浏览器将触发beforeinstallprompt事件。 然后,我们可以使用以下处理程序来处理安装:

- -
window.addEventListener('beforeinstallprompt', (e) => {
-  // Prevent Chrome 67 and earlier from automatically showing the prompt
-  e.preventDefault();
-  // Stash the event so it can be triggered later.
-  deferredPrompt = e;
-  // Update UI to notify the user they can add to home screen
-  addBtn.style.display = 'block';
-
-  addBtn.addEventListener('click', (e) => {
-    // hide our user interface that shows our A2HS button
-    addBtn.style.display = 'none';
-    // Show the prompt
-    deferredPrompt.prompt();
-    // Wait for the user to respond to the prompt
-    deferredPrompt.userChoice.then((choiceResult) => {
-        if (choiceResult.outcome === 'accepted') {
-          console.log('User accepted the A2HS prompt');
-        } else {
-          console.log('User dismissed the A2HS prompt');
-        }
-        deferredPrompt = null;
-      });
-  });
-});
- -

所以我们在这里:

- - - -

点击处理程序包含以下步骤:

- - - -

So when the button is clicked, the install prompt appears.

- -

- -

如果用户选择安装,则将安装该应用程序(可作为独立的桌面应用程序使用),并且不再显示“安装”按钮(如果已经安装了该应用程序,则将不再触发onbeforeinstallprompt事件)。当您打开应用程序时,它将显示在其自己的窗口中:

- -

- -

如果用户选择“取消”,则应用程序的状态将返回到单击按钮之前的状态。

- -
-

注意:本部分的代码主要来自Pete LaPage的应用安装横幅/添加到主屏幕

-
- -

其他

- - - -
{{QuickLinksWithSubpages("/en-US/docs/Web/Progressive_web_apps/")}}
-- cgit v1.2.3-54-g00ecf