웹 사이트를 오프라인에서 작동시키는 방법

그러나 웹사이트는 인터넷에 연결되어 있을 때만 작동합니다. 사용자의 연결이 끊어지면 멋진 사이트 대신 크롬 공룡이 표시됩니다.

그래서 당신의 해결책은 무엇입니까? 당신은 현상 유지를 받아들입니까? 오프라인 웹사이트도 가능합니까?
사실입니다! 프로그레시브 웹 앱(PWA)이 솔루션입니다.
프로그레시브 웹 앱이란 무엇입니까?
프로그레시브 웹 앱은 기본 앱처럼 작동할 수 있는 웹 애플리케이션입니다. 2개의 파일을 사용하여 웹사이트에 푸시 알림, 오프라인 모드를 포함하고 앱처럼 다운로드할 수 있습니다. 이 두 파일을 서비스 워커와 매니페스트 JSON 파일이라고 합니다.
서비스 워커
필요한 첫 번째 파일은 PWA의 두뇌인 자바스크립트 파일인 서비스 워커입니다. 기본 HTML에 스크립트 태그를 추가하고 이 코드를 추가하여 등록해야 합니다.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(function(registration) {
console.log('Service worker started');
})
.catch(function(error) {
console.log('Service worker failed, error:', error);
});
}
별도의
service-worker.js
파일에는 2개의 코드 블록이 필요합니다.self.addEventListener('install', (event) => {
// run caching when installing service worker.
});
self.addEventListener('activate', (event) => {
// After install and all active pages have been closed, this will run.
});
이제 PWA용 시작 코드가 생겼습니다. 나머지 코드 중 일부를 찾아 기능을 추가합니다.
Manjest.json
manifest.json 파일은 노드 프로젝트의 package.json 파일과 유사합니다. 이름, 배경색 및 아이콘과 같은 웹 사이트에 대한 정보가 포함되어 있습니다. 전체 목록은 MDN의 here을 참조하세요. 이 파일은 다운로드할 때 웹 사이트 아이콘이 무엇인지와 같은 일부 웹 앱 메타 데이터를 정의합니다.
루트 HTML 파일의 head 요소에
<link rel="manifest" href="/manifest.json">
를 추가하여 웹사이트를 링크하고 아이콘을 이미지 폴더에 추가합니다.{
"short_name": "My Example PWA",
"name": "Example PWA",
"start_url": "/index.html",
"background_color": "#1c5680",
"display": "standalone",
"theme_color": "#1c5680",
"icons": [
{
"src": "/images/icon.png",
"type": "image/png",
"sizes": "128x128"
}
]
}
오프라인 페이지 만들기
const custom_offline_page = "offline.html"
self.addEventListener('install', event => {
event.waitUntil(
caches.open('CacheName').then((cache) => {
return cache.addAll([
custom_offline_page
])
})
)
})
self.addEventListener("fetch", (event) => {
event.respondWith(
(async () => {
try {
// Fetch request from network
const networkResponse = await fetch(event.request)
return networkResponse
} catch (error) {
// Error thrown when a user has no internet connection
const cache = await caches.open('CacheName')
const cachedResponse = await cache.match(custom_offline_page)
return cachedResponse
}
})()
)
})
이제 오프라인 페이지가 생겼습니다.

작동 테스트
크롬에서 개발자 도구를 열고 등대 탭으로 이동합니다. 감사를 실행할 수 있습니다. 체크 박스 중 하나는 PWA입니다. 감사를 실행하면 문제가 있는 경우 문제가 드러납니다.

개발 도구의
application
탭을 확인하여 매니페스트 json을 보고 서비스 워커가 성공적으로 등록되었는지 확인할 수도 있습니다.고맙다고 커피 한 잔 사주실래요?

질문이나 문제가 있으면 아래 의견에 남겨주세요. 기꺼이 도와드리겠습니다.
자원:
Reference
이 문제에 관하여(웹 사이트를 오프라인에서 작동시키는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/lukeecart/how-to-make-your-website-work-offline-3ick텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)