渐进式 Web 应用结构
在本文中,我们将分析js13kPWA应用程序,它为何以这种方式构建,以及它带来的好处。
该js13kPWA网站结构非常简单:它包含一个 HTML 文件(index.html)以及基本的 CSS 样式(style.css),以及一些图像、脚本和字体。文件夹结构如下所示
HTML
从 HTML 的角度来看,应用外壳是内容部分之外的所有内容
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>js13kGames A-Frame entries</title>
<meta
name="description"
content="A list of A-Frame entries submitted to the js13kGames 2017 competition, used as an example for the MDN articles about Progressive Web Apps." />
<meta name="author" content="end3r" />
<meta name="theme-color" content="#B12A34" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
property="og:image"
content="https://js13kgames.com/img/js13kgames-banner.png" />
<link rel="icon" href="favicon.ico" />
<link rel="stylesheet" href="style.css" />
<link rel="manifest" href="js13kpwa.webmanifest" />
<script src="data/games.js" defer></script>
<script src="app.js" defer></script>
</head>
<body>
<header>
<p>
<a class="logo" href="https://js13kgames.com">
<img src="img/js13kgames.png" alt="js13kGames" />
</a>
</p>
</header>
<main>
<h1>js13kGames A-Frame entries</h1>
<p class="description">
List of games submitted to the
<a href="https://js13kgames.com/aframe">A-Frame category</a> in the
<a href="https://2017.js13kgames.com">js13kGames 2017</a> competition.
You can
<a href="https://github.com/mdn/pwa-examples/blob/main/js13kpwa"
>fork js13kPWA on GitHub</a
>
to check its source code.
</p>
<button id="notifications">Request dummy notifications</button>
<section id="content">// Content inserted in here</section>
</main>
<footer>
<p>
© js13kGames 2012-2018, created and maintained by
<a href="https://end3r.com">Andrzej Mazur</a> from
<a href="https://enclavegames.com">Enclave Games</a>.
</p>
</footer>
</body>
</html>
该<head>
部分包含一些基本信息,例如标题、描述以及指向 CSS、Web 清单、游戏内容 JS 文件和 app.js 的链接 - 这是我们的 JavaScript 应用程序初始化的地方。<body>
被分成<header>
(包含链接的图像)、<main>
页面(带有标题、描述和内容放置区域)和<footer>
(版权信息和链接)。
该应用的唯一作用是列出 js13kGames 2017 比赛中的所有 A-Frame 条目。正如您所看到的,这是一个非常普通的单页面网站 - 目的是使内容简单,以便我们能够专注于实际 PWA 功能的实现。
CSS
CSS 也尽可能简单:它使用@font-face
加载和使用自定义字体,并对 HTML 元素应用一些简单的样式。总体方法是使设计在移动设备(使用响应式 Web 设计方法)和桌面设备上都看起来不错。
主应用 JavaScript
app.js 文件执行了一些我们将在下一篇文章中仔细研究的操作。首先,它根据此模板生成内容
const template = `<article>
<img src='data/img/placeholder.png' data-src='data/img/SLUG.jpg' alt='NAME'>
<h3>#POS. NAME</h3>
<ul>
<li><span>Author:</span> <strong>AUTHOR</strong></li>
<li><span>Website:</span> <a href='http://WEBSITE/'>WEBSITE</a></li>
<li><span>GitHub:</span> <a href='https://GITHUB'>GITHUB</a></li>
<li><span>More:</span> <a href='http://js13kgames.com/entries/SLUG'>js13kgames.com/entries/SLUG</a></li>
</ul>
</article>`;
let content = "";
for (let i = 0; i < games.length; i++) {
let entry = template
.replace(/POS/g, i + 1)
.replace(/SLUG/g, games[i].slug)
.replace(/NAME/g, games[i].name)
.replace(/AUTHOR/g, games[i].author)
.replace(/WEBSITE/g, games[i].website)
.replace(/GITHUB/g, games[i].github);
entry = entry.replace("<a href='http:///'></a>", "-");
content += entry;
}
document.getElementById("content").innerHTML = content;
接下来,它注册了一个服务工作线程
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/pwa-examples/js13kpwa/sw.js");
}
下一个代码块在单击按钮时请求通知权限
const button = document.getElementById("notifications");
button.addEventListener("click", () => {
Notification.requestPermission().then((result) => {
if (result === "granted") {
randomNotification();
}
});
});
最后一个代码块创建通知,这些通知从游戏列表中显示随机选择的项目
function randomNotification() {
const randomItem = Math.floor(Math.random() * games.length);
const notifTitle = games[randomItem].name;
const notifBody = `Created by ${games[randomItem].author}.`;
const notifImg = `data/img/${games[randomItem].slug}.jpg`;
const options = {
body: notifBody,
icon: notifImg,
};
new Notification(notifTitle, options);
setTimeout(randomNotification, 30000);
}
服务工作线程
我们将快速查看的最后一个文件是服务工作线程:sw.js - 它首先从 games.js 文件导入数据
self.importScripts("data/games.js");
接下来,它创建了一个要缓存的所有文件的列表,包括应用外壳和内容
const cacheName = "js13kPWA-v1";
const appShellFiles = [
"/pwa-examples/js13kpwa/",
"/pwa-examples/js13kpwa/index.html",
"/pwa-examples/js13kpwa/app.js",
"/pwa-examples/js13kpwa/style.css",
"/pwa-examples/js13kpwa/fonts/graduate.eot",
"/pwa-examples/js13kpwa/fonts/graduate.ttf",
"/pwa-examples/js13kpwa/fonts/graduate.woff",
"/pwa-examples/js13kpwa/favicon.ico",
"/pwa-examples/js13kpwa/img/js13kgames.png",
"/pwa-examples/js13kpwa/img/bg.png",
"/pwa-examples/js13kpwa/icons/icon-32.png",
"/pwa-examples/js13kpwa/icons/icon-64.png",
"/pwa-examples/js13kpwa/icons/icon-96.png",
"/pwa-examples/js13kpwa/icons/icon-128.png",
"/pwa-examples/js13kpwa/icons/icon-168.png",
"/pwa-examples/js13kpwa/icons/icon-192.png",
"/pwa-examples/js13kpwa/icons/icon-256.png",
"/pwa-examples/js13kpwa/icons/icon-512.png",
];
const gamesImages = [];
for (let i = 0; i < games.length; i++) {
gamesImages.push(`data/img/${games[i].slug}.jpg`);
}
const contentToCache = appShellFiles.concat(gamesImages);
下一个代码块安装服务工作线程,然后实际缓存上述列表中包含的所有文件
self.addEventListener("install", (e) => {
console.log("[Service Worker] Install");
e.waitUntil(
(async () => {
const cache = await caches.open(cacheName);
console.log("[Service Worker] Caching all: app shell and content");
await cache.addAll(contentToCache);
})(),
);
});
最后,如果缓存中存在内容,服务工作线程将从缓存中获取内容,从而提供离线功能
self.addEventListener("fetch", (e) => {
e.respondWith(
(async () => {
const r = await caches.match(e.request);
console.log(`[Service Worker] Fetching resource: ${e.request.url}`);
if (r) {
return r;
}
const response = await fetch(e.request);
const cache = await caches.open(cacheName);
console.log(`[Service Worker] Caching new resource: ${e.request.url}`);
cache.put(e.request, response.clone());
return response;
})(),
);
});
JavaScript 数据
游戏数据以 JavaScript 对象的形式存在于 data 文件夹中(games.js)
const games = [
{
slug: "lost-in-cyberspace",
name: "Lost in Cyberspace",
author: "Zosia and Bartek",
website: "",
github: "github.com/bartaz/lost-in-cyberspace",
},
{
slug: "vernissage",
name: "Vernissage",
author: "Platane",
website: "github.com/Platane",
github: "github.com/Platane/js13k-2017",
},
// ...
{
slug: "emma-3d",
name: "Emma-3D",
author: "Prateek Roushan",
website: "",
github: "github.com/coderprateek/Emma-3D",
},
];
每个条目在 data/img 文件夹中都有自己的图像。这是我们的内容,使用 JavaScript 加载到内容部分。