PWA技术及其用户体验设计
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>Max</title>
<meta name="description" content="app的介绍">
<meta name="author" content="作者">
<meta name="theme-color" content="#B12A34">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="og:image" content="icons/icon-512.png">
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" href="style.css">
<link rel="manifest" href="manifest.json">
<script src="app.js" defer></script>
</head>
<body>
<header>
<p>MAX-demo</p>
</header>
<main>
<h1>HELLO WORLD</h1>
<button id="notifications">Request notifications</button>
<section id="content">
// Content inserted in here
</section>
</main>
<footer>
<p>© max 2012-2018, created and maintained by shadow.</p>
</footer>
</body>
</html>
- Service Worker
缓存机制是依赖 Cache API 实现的
依赖 HTML5 fetch API 发起网络请求
依赖 Promise 实现异步
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/serviceWorker.js', { scope: '/' })
.then(function(registration) {
// 注册成功
console.log('ServiceWorker registration successful with scope: ', registration.scope);
})
.catch(function(err) {
// 注册失败
console.log('ServiceWorker registration failed: ', err);
});
});
};
let cacheName = 'max-v1';
let contentToCache = [
'/',
'/index.html',
'/style.css',
'/app.js'
];
// 对app shell和主体内容(content)里面的数据创建缓存
self.addEventListener('install', function(e) {
console.log('[Service Worker] Install');
e.waitUntil(
// 安装成功后操作 CacheStorage 缓存,使用之前需要先通过 caches.open() 打开对应缓存空间。
caches.open(cacheName).then(function(cache) {
console.log('[Service Worker] Caching all: app shell and content');
// 通过 cache 缓存对象的 addAll 方法添加 缓存
return cache.addAll(contentToCache);
})
);
});
//如果条件允许,service worker将从缓存中请求content中所需的数据,从而提供离线应用功能
self.addEventListener('fetch', function(e) {
e.respondWith(
caches.match(e.request).then(function(r) {
console.log('[Service Worker] Fetching resource: ' + e.request.url);
return r || fetch(e.request).then(function(response) {
return caches.open(cacheName).then(function(cache) {
console.log('[Service Worker] Caching new resource: ' + e.request.url);
cache.put(e.request, response.clone());
return response;
});
});
})
);
});
- 添加至桌面功能
{
"name": "max-demo-v1",
"short_name": "max",
"description": "demo",
"icons": [{
"src": "icons/mix-logo.png",
"sizes": "72x72 96x96 128x128 256x256",
"type": "image/png"
}],
"start_url": "/index.html",
"display": "fullscreen",
"theme_color": "#4a4a4a",
"background_color": "#eeeeee"
}
- 如何告知普通用户什么是离线模式?或者什么是PWA?
赞 (0)