<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ PWA渐进式Web应用 - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ freeCodeCamp 是一个免费学习编程的开发者社区，涵盖 Python、HTML、CSS、React、Vue、BootStrap、JSON 教程等，还有活跃的技术论坛和丰富的社区活动，在你学习编程和找工作时为你提供建议和帮助。 ]]>
        </description>
        <link>https://www.freecodecamp.org/chinese/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ PWA渐进式Web应用 - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/chinese/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 26 May 2026 20:24:25 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/chinese/news/tag/progressive-web-app/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ 从零开始使用 HTML、CSS 和 JavaScript 搭建 PWA ]]>
                </title>
                <description>
                    <![CDATA[ 原文：How to build a PWA from scratch with HTML, CSS, and JavaScript [https://www.freecodecamp.org/news/build-a-pwa-from-scratch-with-html-css-and-javascript/] ，作者：Ibrahima Ndaw [https://www.freecodecamp.org/news/author/ibrahima92/] 渐进式 Web 应用是一种能给传统 Web 应用带来原生应用体验的方式。使用 PWA ，我们能够使用移动应用的特性来增强我们的网站，从而提高网站的可用性，并提供良好的用户体验。 在这篇文章中，我们将使用 HTML、CSS 和 JavaScript 从零开始构建 PWA。我们要讨论的主题有：  * 什么是渐进式 Web App ?  * 标记  * 样式  * 用 JavaScript 显示数据  * Web 应用 ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/build-a-pwa-from-scratch-with-html-css-and-javascript/</link>
                <guid isPermaLink="false">603cc75dc354c605689eaad4</guid>
                
                    <category>
                        <![CDATA[ PWA渐进式Web应用 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ reset0 ]]>
                </dc:creator>
                <pubDate>Wed, 13 Apr 2022 02:50:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2021/03/Group-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>原文：<a href="https://www.freecodecamp.org/news/build-a-pwa-from-scratch-with-html-css-and-javascript/">How to build a PWA from scratch with HTML, CSS, and JavaScript</a>，作者：<a href="https://www.freecodecamp.org/news/author/ibrahima92/">Ibrahima Ndaw</a></p><!--kg-card-begin: markdown--><p>渐进式 Web 应用是一种能给传统 Web 应用带来原生应用体验的方式。使用 PWA ，我们能够使用移动应用的特性来增强我们的网站，从而提高网站的可用性，并提供良好的用户体验。</p>
<p>在这篇文章中，我们将使用 HTML、CSS 和 JavaScript 从零开始构建 PWA。我们要讨论的主题有：</p>
<ul>
<li>什么是渐进式 Web App ?</li>
<li>标记</li>
<li>样式</li>
<li>用 JavaScript 显示数据</li>
<li>Web 应用 Manifest</li>
<li>什么是 Service Worker?</li>
<li>缓存资源</li>
<li>获取资源</li>
<li>注册 Service Worker</li>
<li>最后的想法</li>
<li>更多资源</li>
</ul>
<p>那么，让我们从一个重要的问题开始：PWA 到底是什么？</p>
<h2 id="webapp">什么是渐进式 Web App ?</h2>
<p>渐进式 Web 应用是一种通过使用现代 Web 能力向用户提供类似于应用程序的体验的 Web 应用程序。总而言之，它只是一个运行在浏览器上且使用了一些增强特性的普通网站。它赋予你以下的能力：</p>
<ul>
<li>安装到你的手机桌面上</li>
<li>离线访问</li>
<li>使用摄像头</li>
<li>通知推送</li>
<li>后台同步</li>
</ul>
<p>等等。</p>
<p>但是，为了将传统的 Web 应用转换成 PWA，我们必须对其做出一些小调整，添加一个 manifest 文件和 service worker。</p>
<p>别担心这些新术语，我们将会在下面介绍它们。</p>
<p>首先，我们必须要构建传统的 Web 应用，所以让我们从编写结构开始吧。</p>
<h2 id="">标记</h2>
<p>这个 HTML 文件十分简单，我们只需要将所有内容放置在 <code>main</code> 标签内即可</p>
<ul>
<li>在 <code>index.html</code></li>
</ul>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
    &lt;head&gt;
        &lt;meta charset="UTF-8" /&gt;
        &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;
        &lt;meta http-equiv="X-UA-Compatible" content="ie=edge" /&gt;
        &lt;link rel="stylesheet" href="css/style.css" /&gt;
        &lt;title&gt;Dev'Coffee PWA&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;main&gt;
            &lt;nav&gt;
                &lt;h1&gt;Dev'Coffee&lt;/h1&gt;
                &lt;ul&gt;
                    &lt;li&gt;Home&lt;/li&gt;
                    &lt;li&gt;About&lt;/li&gt;
                    &lt;li&gt;Blog&lt;/li&gt;
                &lt;/ul&gt;
            &lt;/nav&gt;
            &lt;div class="container"&gt;&lt;/div&gt;
        &lt;/main&gt;
        &lt;script src="js/app.js"&gt;&lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>然后用 <code>nav</code> 标签来创建一个导航栏。用 <code>div</code> 标签来创建一个 class 为 <code>container</code> 的元素来放置剩下的卡片，稍后我们将使用 Javascript 来添加它们。</p>
<p>现在我们把这些都弄好了，让我们用 CSS 来给它加点样式。</p>
<h2 id="">样式</h2>
<p>向往常一样，我们需要先引入一些字体。然后我们再重置某些默认样式。</p>
<ul>
<li>在 <code>css/style.css</code></li>
</ul>
<pre><code class="language-css">@import url('https://fonts.googleapis.com/css?family=Nunito:400,700&amp;display=swap');
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body {
    background: #fdfdfd;
    font-family: 'Nunito', sans-serif;
    font-size: 1rem;
}
main {
    max-width: 900px;
    margin: auto;
    padding: 0.5rem;
    text-align: center;
}
nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
ul {
    list-style: none;
    display: flex;
}
</code></pre>
<p>然后我们限制 <code>main</code> 元素的最大宽度为 <code>900px</code>让它在大屏幕上看起来有更好的呈现方式。</p>
<p>对于导航栏 ，我希望 logo 在左边，链接在右边。所以对于 <code>nav</code> 标签，将其设为 flex 容器后，我们使用 <code>justify-content: space-between;</code> 将其对齐。</p>
<ul>
<li>在 <code>css/style.css</code></li>
</ul>
<pre><code class="language-css">.container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));
    grid-gap: 1rem;
    justify-content: center;
    align-items: center;
    margin: auto;
    padding: 1rem 0;
}
.card {
    display: flex;
    align-items: center;
    flex-direction: column;
    width: 15rem auto;
    height: 15rem;
    background: #fff;
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
    border-radius: 10px;
    margin: auto;
    overflow: hidden;
}
.card--avatar {
    width: 100%;
    height: 10rem;
    object-fit: cover;
}
.card--title {
    color: #222;
    font-weight: 700;
    text-transform: capitalize;
    font-size: 1.1rem;
    margin-top: 0.5rem;
}
.card--link {
    text-decoration: none;
    background: #db4938;
    color: #fff;
    padding: 0.3rem 1rem;
    border-radius: 20px;
}
</code></pre>
<p>我们有几个卡片，所以 container 元素将使用 grid 布局来显示。然后添加属性 <code>grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr))</code>，我们现在能够使卡片具有响应式。这样的话如果有足够空间它们将最少具有 <code>15rem</code> 的宽度（如果没有则足够的空间则使用 <code>1fr</code>）。</p>
<p>然后为了使它们更加好看，我们在 <code>.card</code> 类上添加了双倍的阴影效果，并在 <code>.card--avatar</code> 上使用 <code>object-fit: cover</code> 属性为了防止图像的拉伸</p>
<p>现在它看起来更好看了，但是我们仍然没有数据显示。</p>
<p>让我们在下一节来解决这个问题。</p>
<h2 id="javascript">使用 JavaScript 显示数据</h2>
<p>请注意，我使用了较大的图片，加载它会需要一些时间。这将以最好的方式向你展示 service workers 的能力。</p>
<p>正如我之前说过用 Class 名为 <code>.container</code> 的元素保存我们的卡片，因此我们需要选择它。</p>
<ul>
<li>在 <code>js/app.js</code></li>
</ul>
<pre><code class="language-javascript">const container = document.querySelector('.container');
const coffees = [
    { name: 'Perspiciatis', image: 'images/coffee1.jpg' },
    { name: 'Voluptatem', image: 'images/coffee2.jpg' },
    { name: 'Explicabo', image: 'images/coffee3.jpg' },
    { name: 'Rchitecto', image: 'images/coffee4.jpg' },
    { name: ' Beatae', image: 'images/coffee5.jpg' },
    { name: ' Vitae', image: 'images/coffee6.jpg' },
    { name: 'Inventore', image: 'images/coffee7.jpg' },
    { name: 'Veritatis', image: 'images/coffee8.jpg' },
    { name: 'Accusantium', image: 'images/coffee9.jpg' },
];
</code></pre>
<p>然后，我们创建一个包含名字和图片的卡片数组。</p>
<ul>
<li>在 <code>js/app.js</code></li>
</ul>
<pre><code class="language-javascript">const showCoffees = () =&gt; {
  let output = ""
  coffees.forEach(
    ({ name, image }) =&gt;
      (output += `
              &lt;div class="card"&gt;
                &lt;img class="card--avatar" src=${image} /&gt;
                &lt;h1 class="card--title"&gt;${name}&lt;/h1&gt;
                &lt;a class="card--link" href="#"&gt;Taste&lt;/a&gt;
              &lt;/div&gt;
              `)
  )
  container.innerHTML = output
}

document.addEventListener("DOMContentLoaded", showCoffees)

</code></pre>
<p>有了上面的代码，我们现在能够通过遍历数组并将其显示在 HTML 上。为了保证工作正常，我们等待 DOM （文档对象模型）内容加载完成再执行 <code>showCoffees</code> 方法。</p>
<p>我们已经做了很多了，但现在我们只有一个传统的 Web 应用。所以，让我们在下一节通过引入一些 PWA 的特性来改变这种情况。</p>
<p><img src="https://media.giphy.com/media/l3V0dy1zzyjbYTQQM/source.gif" alt="super-excited" width="600" height="400" loading="lazy"></p>
<h2 id="webmanifest">Web 应用 Manifest</h2>
<p>web 应用 manifest 是一个简单的 JSON 文件，它向浏览器告知你的 web 应用。它告诉浏览器在移动设备或桌面安装时该如何表现。而要显示”添加到主屏幕“的提示，则需要 web 应用 manifest。</p>
<p>现在我们知道 web manifest 是什么了，让我们在根目录创建一个名为 <code>manifest.json</code> 的新文件（你得这样命名）。然后在里面添加这些代码。</p>
<ul>
<li>在 <code>manifest.json</code></li>
</ul>
<pre><code class="language-javascript">{
  "name": "Dev'Coffee",
  "short_name": "DevCoffee",
  "start_url": "index.html",
  "display": "standalone",
  "background_color": "#fdfdfd",
  "theme_color": "#db4938",
  "orientation": "portrait-primary",
  "icons": [
    {
      "src": "/images/icons/icon-72x72.png",
      "type": "image/png", "sizes": "72x72"
    },
    {
      "src": "/images/icons/icon-96x96.png",
      "type": "image/png", "sizes": "96x96"
    },
    {
      "src": "/images/icons/icon-128x128.png",
      "type": "image/png","sizes": "128x128"
    },
    {
      "src": "/images/icons/icon-144x144.png",
      "type": "image/png", "sizes": "144x144"
    },
    {
      "src": "/images/icons/icon-152x152.png",
      "type": "image/png", "sizes": "152x152"
    },
    {
      "src": "/images/icons/icon-192x192.png",
      "type": "image/png", "sizes": "192x192"
    },
    {
      "src": "/images/icons/icon-384x384.png",
      "type": "image/png", "sizes": "384x384"
    },
    {
      "src": "/images/icons/icon-512x512.png",
      "type": "image/png", "sizes": "512x512"
    }
  ]
}

</code></pre>
<p>最后，这个 JSON 文件具有一些可填和必填的属性。</p>
<p>name: 当浏览器显示启动画面时，在屏幕上显示的名称。</p>
<p>short_name: 你的 app 在主屏幕上显示的快捷方式的名称。</p>
<p>start_url: 当你的 app 打开时，所要显示的页面。</p>
<p>display: 告诉浏览器如何显示你的 app。有几种模式可以选择，如<code>minimal-ui</code>、<code>fullscreen</code>、<code>browser</code>等等。这里我们使用<code>standalone</code>模式来隐藏与浏览器有关的任何内容。</p>
<p>background_color: 当浏览器显示启动画面时，指定屏幕的背景颜色。</p>
<p>theme_color: 当我们打开 app 的时候指定状态栏的背景颜色。</p>
<p>orientation: 告诉浏览器显示 app 时的方向。</p>
<p>icons： 当浏览器显示启动画面时，在屏幕上显示的图标。我们在这里使用了所有尺寸以及任何设备的首选图标，但是你只能选择一到两个，由你决定。</p>
<p>现在我们有了一个 web 应用的 manifest，让我们来将它添加到 html 文件中。</p>
<ul>
<li>在 <code>index.html</code> (head 标签中)</li>
</ul>
<pre><code class="language-html">&lt;link rel="manifest" href="manifest.json" /&gt;
&lt;!-- ios support --&gt;
&lt;link rel="apple-touch-icon" href="images/icons/icon-72x72.png" /&gt;
&lt;link rel="apple-touch-icon" href="images/icons/icon-96x96.png" /&gt;
&lt;link rel="apple-touch-icon" href="images/icons/icon-128x128.png" /&gt;
&lt;link rel="apple-touch-icon" href="images/icons/icon-144x144.png" /&gt;
&lt;link rel="apple-touch-icon" href="images/icons/icon-152x152.png" /&gt;
&lt;link rel="apple-touch-icon" href="images/icons/icon-192x192.png" /&gt;
&lt;link rel="apple-touch-icon" href="images/icons/icon-384x384.png" /&gt;
&lt;link rel="apple-touch-icon" href="images/icons/icon-512x512.png" /&gt;
&lt;meta name="apple-mobile-web-app-status-bar" content="#db4938" /&gt;
&lt;meta name="theme-color" content="#db4938" /&gt;
</code></pre>
<p>如你所看到的，我们在 head 标签里引入了<code>manifest.json</code>文件。并且还引入了一些其他文件来处理 IOS 上的图标显示、状态栏颜色和主题色。</p>
<p>现在我们可以深入探讨最后一步并介绍 service worker。</p>
<h2 id="serviceworker">什么是 Service Worker?</h2>
<p>需要注意的是，由于 service worker 能够访问并处理请求，所以 PWA 仅在 https 上运行。因此安全是必须的。</p>
<p>service worker 是浏览器在后台的独立线程中运行的脚本。这意味着它将在不同的地方运行，并且与你的页面完全隔离，这就是为什么它不能操纵你的 DOM 元素的原因。</p>
<p>不过，它的功能超级强大。service worker 能拦截并处理网络请求，管理缓存以实现离线访问或者向你的用户推送通知。</p>
<p><img src="https://media.giphy.com/media/5VKbvrjxpVJCM/source.gif" alt="wow" width="600" height="400" loading="lazy"></p>
<p>所以让我们在根目录下创建第一个 service worker，并命名为<code>serviceWorker.js</code>(名称由你决定)。但是你必须将它放在根目录上，这样你就不会把它的范围限制在一个文件夹里。</p>
<h3 id="">资源缓存</h3>
<ul>
<li>在 <code>serviceWorker.js</code></li>
</ul>
<pre><code class="language-javascript">const staticDevCoffee = 'dev-coffee-site-v1';
const assets = [
    '/',
    '/index.html',
    '/css/style.css',
    '/js/app.js',
    '/images/coffee1.jpg',
    '/images/coffee2.jpg',
    '/images/coffee3.jpg',
    '/images/coffee4.jpg',
    '/images/coffee5.jpg',
    '/images/coffee6.jpg',
    '/images/coffee7.jpg',
    '/images/coffee8.jpg',
    '/images/coffee9.jpg',
];
</code></pre>
<p>这段代码看起来有点吓人，但它只是 JavaScript 而已（所以别担心）。</p>
<p>我们声明了缓存的名称<code>staticDevCoffee</code>和要储存在缓存中的资源。为了执行这些操作，我们需要给<code>self</code>添加一个监听器。</p>
<p><code>self</code>就是 service worker 本身。它能够让我们监听生命周期中的事件并做一些对应的事情。</p>
<p>service worker 有几个生命周期，其中之一是 <code>install</code> 事件。当 service worker 被安装时，它就会运行。它在 worker 执行后立即触发，而且每个 service worker 只调用一次。</p>
<p>当<code>install</code>事件触发时，回调函数将被调用，通过这个回调函数我们可以访问<code>event</code>对象。</p>
<p>在浏览器上缓存某些内容的时候可能需要一些时间才能完成，因为它是异步的。</p>
<p>为了处理这个问题，我们需要使用<code>waitUntil()</code>。正如你所猜的这样，它会等待操作完成。</p>
<p>一旦 cache API 准备就绪，我们可以执行<code>open()</code>方法，并通过将缓存名称当作参数传递给<code>caches.open(staticDevCoffee)</code>来创建我们的缓存。</p>
<p>它会返回一个 promise，将帮助我们使用<code>cache.addAll(assets)</code>将我们的资源储存在缓存中。</p>
<p><img src="https://drive.google.com/uc?id=1ynBQRQ00wHo5J6CnjfLCX3b3UNiSrGqZ" alt="image-cache" width="600" height="400" loading="lazy"></p>
<p>希望你能理解这些内容。</p>
<p><img src="https://media.giphy.com/media/OQEcw90jACeU8/source.gif" alt="desesperate" width="600" height="400" loading="lazy"></p>
<p>现在，我们已经顺利的把资源缓存到浏览器中。而下次我们加载页面时，如果我们处于离线状态， service worker 将会处理该请求并获取缓存。</p>
<p>所以，让我们取回我们的缓存吧。</p>
<h3 id="">获取资源</h3>
<ul>
<li>在 <code>serviceWorker.js</code></li>
</ul>
<pre><code class="language-javascript">self.addEventListener('fetch', (fetchEvent) =&gt; {
    fetchEvent.respondWith(
        caches.match(fetchEvent.request).then((res) =&gt; {
            return res || fetch(fetchEvent.request);
        })
    );
});
</code></pre>
<p>Here, we use the <code>fetch</code> event to, well, get back our data. The callback gives us access to <code>fetchEvent</code>. Then we attach <code>respondWith()</code> to prevent the browser's default response. Instead it returns a promise because the fetch action can take time to finish.</p>
<p>这里，我们使用<code>fetch</code>事件来获取我们的数据，通过回调函数我们可以访问<code>fetchEvent</code>。我们添加<code>respondWith()</code> 来阻止浏览器的默认响应。然后返回一个 promise，因为 fetch 操作可能需要一些时间才能完成。</p>
<p>当一个缓存准备就绪时，我们将使用 <code>caches.match(fetchEvent.request)</code>。它将检查缓存中是否有与<code>fetchEvent.request</code>匹配的内容。顺便一提，<code>fetchEvent.request</code>只是我们的 assets 数组。</p>
<p>然后，它会返回一个 promise。如果缓存存在，我们可以直接返回它，否则则返回最初的 fetch。</p>
<p>现在， 我们的资源可以被 service worker 缓存并获取，这将大大的优化了我们的图片的加载时间。</p>
<p>最重要的是，它使我们的应用可以在离线模式下使用。</p>
<p>但现在 service worker 还不能工作，我们还需要在我们的项目中注册它。</p>
<p><img src="https://media.giphy.com/media/Z9EvIRmLEOS3JNFeVb/source.gif" alt="let-s-do-it" width="600" height="400" loading="lazy"></p>
<h2 id="serviceworker">注册 Service Worker</h2>
<ul>
<li>在 <code>js/app.js</code></li>
</ul>
<pre><code class="language-javascript">if ('serviceWorker' in navigator) {
    window.addEventListener('load', function () {
        navigator.serviceWorker
            .register('/serviceWorker.js')
            .then((res) =&gt; console.log('service worker registered'))
            .catch((err) =&gt; console.log('service worker not registered', err));
    });
}
</code></pre>
<p>在这里，我们先检查当前浏览器是否支持<code>serviceWorker</code>（因为并未所有的浏览器都支持它）。</p>
<p>然后，我们将监听页面的 load 事件来注册我们的 service worker。通过传递文件名<code>serviceWorker.js</code>作为参数给<code>navigator.serviceWorker.register()</code>来作为注册 service worker 的参数。</p>
<p>通过上述步骤，我们现在已经将传统的 web 应用转换成为 PWA。</p>
<p><img src="https://media.giphy.com/media/3o6ZtlGkjeschymLNm/source.gif" alt="we-did-it" width="600" height="400" loading="lazy"></p>
<h2 id="">最后的想法</h2>
<p>在本文中，我们已经看到了 PWA 的神奇之处。通过添加一个 web 应用 manifest 和一个 service worker，确实提高了我们传统 web 应用的用户体验。这是因为 PWA 快速、安全、可靠，更重要的是它支持离线模式。</p>
<p>现在很多的框架都已经为我们设置了好了 service worker 文件。但是知道如何用 Vanilla JavaScript 来实现它可以帮你理解 PWA。</p>
<p>而且你还可通过动态缓存资源或者限制缓存大小等方法更进一步的使用 service worker。</p>
<p>感谢你阅读本文。</p>
<p>你可以在线上<a href="https://devcoffee-pwa.netlify.com/">浏览</a>，源代码在<a href="https://github.com/ibrahima92/pwa-with-vanilla-js">这里</a>。</p>
<p>在我的博客上阅读我的更多文章。</p>
<h2 id="">更多资源</h2>
<p><a href="https://developers.google.com/web/fundamentals/web-app-manifest">Web Manifest 文档</a></p>
<p><a href="https://developers.google.com/web/fundamentals/primers/service-workers">Service Worker 文档</a></p>
<p><a href="https://app-manifest.firebaseapp.com/">Web Manifest 生成器</a></p>
<p><a href="https://caniuse.com/#search=service%20worker">浏览器支持</a></p>
<!--kg-card-end: markdown--> ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
