0

我曾经像这样通过 vanilla javascript 编写 pwa

importScripts('/src/js/idb.js');
importScripts('/src/js/utility.js');

const CACHE_STATIC_NAME = 'static-v4';
const CACHE_DYNAMIC_NAME = 'dynamic-v2';
const STATIC_FILES = [
  '/',
  '/index.html',
  '/offline.html',
  '/src/js/app.js',
  '/src/js/feed.js',
  '/src/js/promise.js',
  '/src/js/fetch.js',
  '/src/js/idb.js',
  '/src/js/material.min.js',
  '/src/css/app.css',
  '/src/css/feed.css',
  '/src/images/main-image.jpg',
  'https://fonts.googleapis.com/css?family=Roboto:400,700',
  'https://fonts.googleapis.com/icon?family=Material+Icons',
  'https://cdnjs.cloudflare.com/ajax/libs/material-design-lite/1.3.0/material.indigo-pink.min.css'
 ];

 self.addEventListener('install', function(e) {
    e.waitUntil(
      caches.open(CACHE_STATIC_NAME)
       .then(function(cache) {
           console.log('[Service Worker] Installing Service Worker ...');
              cache.addAll(STATIC_FILES);
       })
    );
 });

 self.addEventListener('activate', function(e) {
    console.log('[Service Worker] Activating Service Worker ...');

    // clear old cache
    e.waitUntil(
        caches.keys()
          .then(function(cachedKeys) {
              return Promise.all(cachedKeys.map(function(key) {
                  if(key !== CACHE_STATIC_NAME && key !== CACHE_DYNAMIC_NAME) {
                    return caches.delete(key);
                  }
              }))
          })
    );
// Tell the active service worker to take control of the page immediately.
    return self.clients.claim(); // to ensure that activating is correctly done
});

//After install, fetch event is triggered for every page request
self.addEventListener('fetch', function(event) {
  let url = 'https://pwa-training-4a918.firebaseio.com/posts.json';

  if(event.request.url === url) {
    event.respondWith( 
      fetch(event.request).then(res => {
          let clonedRes = res.clone();
          // in order to clear ol data if new data is different from the original one
          clearAllData('posts')
            .then(() => {
              return clonedRes.json()
            })
            .then(data => {
              for(let key in data) {
                writeData('posts', data[key])
              }
            });


          return res;
        })
      );
    // USE Cache only Strategy if the request is in the static Files
  } else if(STATIC_FILES.includes(event.request.url)) {
    event.respondWith(
      caches.match(event.request)
    ); 
  } else {
    event.respondWith(
      caches.match(event.request).then(response => {
        return response || fetch(event.request).then(response => {
          return caches.open(CACHE_DYNAMIC_NAME).then(cache => {
            cache.put(event.request, response.clone());
  
            return response;
          })
        })
      })
      .catch(err => {
        return caches.open(CACHE_STATIC_NAME).then(cache => {
          // i need to show offline page only if the failure is in the help Page
          // because it does not make any sence if i show this page in case of the failure in files like css 
          if(event.request.headers.get('accept').includes('text/html')) {
            return cache.match('/offline.html');
          }
        })
      })
    );
  }
});

但是当我尝试在 vuejs 应用程序中编写自己的应用程序时,我通过vue add pwa它为我创建了一个名为registerServiceWorker.js我不理解的文件安装了 pwa,因为我不习惯使用它

在此处输入图像描述

该文件包含以下内容

/* eslint-disable no-console */

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n' +
      )
    },
    registered () {
      console.log('Service worker has been registered.')
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    updatefound () {
      console.log('New content is downloading.')
    },
    updated () {
      console.log('New content is available; please refresh.')
    },
    offline () {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
      console.error('Error during service worker registration:', error)
    }
  })
}

我不知道如何在这里编写自己的 pwa 代码或在哪里可以这样做?另外我不知道它是否可以在本地主机上工作,因为据我所知,它可以在生产环境中工作

所以我的问题是,我如何像以前在 vue 应用程序中使用 vanilla js 那样编写 PWA?为了完成我的完整自定义 PWA,我应该执行哪些步骤?

我可以在不使用工作箱的情况下做到这一点吗?

如果有人可以帮助我,我将不胜感激。

提前致谢。

4

1 回答 1

1

我/(我们中的大多数人)不太可能在任何项目中从头开始重做 service worker,除了 Vue CLI 之外,Workbox 也是 Google Developers页面中推荐的工具。

作为registerServiceWorker.js,这是您的应用程序中的服务工作者周期的样板,因为日志在您的应用程序流程中非常简单

如果您仍想从头开始,我建议您阅读https://developers.google.com/web/fundamentals/primers/service-workers/以了解基础知识。我会推荐,因为service-worker几乎“我希望你知道你用你的应用程序做了什么,比如什么时候更新/缓存/离线时做/”

于 2020-04-22T20:21:30.553 回答