Mohammed Saber
Mohammed Saber

Reputation: 50

How to write PWA in Vue js?

i used to write pwa via vanilla javascript like this

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');
          }
        })
      })
    );
  }
});

but when I'm trying to write my own in vuejs app I installed pwa via vue add pwa it created for me a file called registerServiceWorker.js that I don't understand because I'm not used to use it

enter image description here

This file contains the following

/* 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)
    }
  })
}

I don't know how to write my own pwa code here or where I can do that? Also I don't know if it will work on localhost or not because from what I'm noticing it works in Production

So My Question is, How Can I Write PWA As I used to do with vanilla js in vue app? What are the steps should I do in order to accomplish my full custom PWA?

Can I Do That without using workbox?

if anyone can help me i'll be appreciated.

Thanks in advance.

Upvotes: 0

Views: 603

Answers (1)

SC Kim
SC Kim

Reputation: 600

I/(pretty sure most of us) won't likely throw to redo service worker from scratch in any project, Workbox is also recommended tools in Google Developers' page other than Vue CLI.

As the registerServiceWorker.js, that's boilerplate for your service worker cycle in your App, as the logs pretty straightforward in the flow of your app process

If you wanna to do from scratch still, i would suggest read https://developers.google.com/web/fundamentals/primers/service-workers/ to understand the fundamentals. I would recommend because service-worker pretty much "I hope you know what you doing with your app like what-when-to update/caching/do-when-offline/"

Upvotes: 1

Related Questions