LoginSignup
2
2

【PWA + GitHub】10分でできるPWAの導入

Posted at

はじめに

PWAを手っ取り早く実現してどんなものかを確かめたいという人向けの記事です。

前提条件

  • httpsでwebページを公開する環境が整っている
  • GitHubの基本的な使い方を理解している

目次

  1. PWAを導入する
  2. 参考文献

PWAを導入する

ファイルの作成

GitHub上に以下の構成でリポジトリを作成します(sw.jsのurlsToCacheにはリポジトリ名を入れてください)

index.html
<!DOCTYPE html>
<html>
<head>
	<title>Your App</title>
	<link rel="manifest" href="manifest.json">
<script>
if ('serviceWorker' in navigator) {
	window.addEventListener('load', () => {
	navigator.serviceWorker.register('sw.js').then(registration => {
	console.log('ServiceWorker registration successful with scope: ', registration.scope);
	}, err => {
	console.log('ServiceWorker registration failed: ', err);
	}).catch(err => {
	console.log(err)
	});
	});
}
</script>
</head>
<body>
	<h1>hello world</h1>
</body>
</html>
manifest.json
{
	"short_name": "pwa",
	"name": "pwa_sample_app",
	"display": "standalone",
	"start_url": "index.html",
	"icons": [
		{
			"src": "images/icon.png",
			"sizes": "192x192",
			"type": "image/png"
		}
	]
}
sw.js
var CACHE_NAME = 'pwa-sample-caches';
var urlsToCache = [
	'/pwa/',
];

// インストール処理
self.addEventListener('install', function(event) {
	event.waitUntil(
		caches
			.open(CACHE_NAME)
			.then(function(cache) {
				return cache.addAll(urlsToCache);
			})
	);
});

self.addEventListener('fetch', function(event) {
	event.respondWith(
		caches
			.match(event.request)
			.then(function(response) {
				return response ? response : fetch(event.request);
			})
	);
});

最後にimages/icon.pngを配置して完了です。最終的には以下の構成になるはずです。

image.png

アクセスしてみる

作成したwebページにhttpsでアクセスします(やり方がわからない人は以下の記事を参考にアクセスしてください)

iphoneでアクセスした場合、ホーム画面に追加を行ってアクセスするとurlが表示されず、アプリを起動したときのような振る舞いになります。

IMG_2922.PNG

以上で作業完成です

参考文献

この記事は以下のサイトを参考に作成しました

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2