Create base Pwa App#2 : Service worker installation, Activate Service worker, and Fetch cache

in utopian-io •  26 days ago

Repository

https://github.com/jquery/jquery

What Will I Learn?

  • Service worker installation
  • Activate Service worker
  • Fetch cache

Requirements

  • Basic Html, CSS, javascript
  • Install Jquery and basic Jquery
  • Local server (Xampp, Wampp, or etc)

Resources

Difficulty

Basic

Tutorial Content

This tutorial is a continuation of the Pwa application tutorial that we have learned in the previous tutorial , in the previous tutorial we have learned and recognized parts of the Pwa application. this time we will discuss more deeply and will provide clearer examples, we will continue the Pwa application that we have made previously, we have made the API client and have consumed it on our Pwa application. for that, I suggest you see the first part of the tutorial series this time.

Service worker installation

-- Register check

We have registered in the previous tutorial now we will check whether the registration is running properly, we will do the console, .log() to check it.the following is the code.

if ('serviceWorker' in navigator) {
         window.addEventListener('load', function() {
            navigator.serviceWorker.register('sw.js').then(function(registration){
                console.log(registration)
                console.log("registration has been successful " + registration.scope)
            },function(err){
                console.log(err)
            });
        });
    }
  • I will do console.log (registration) to see what data we can when we successfully register, we will see more details in the picture below.

ezgif.com-video-to-gif (2).gif

In the previous [tutorial] (https://steemit.com/utopian-io/@duski.harahap/create-bot-terminal-with-jquery-4-previous-and-next-command-and-create-object-in-bot-1537231788514)we have created the sw.js file that we use as a service worker and we have also registered the file as a service worker. now all we have to do is install and define the file service worker, we can do it like the code below.

sw.js

var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
  '/',
  'assets/main.css',
  'js/main.js',
    'js/jquery.min.js'
];
self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});
  • Install service workers: We can install the service worker in the sw.js file this way self.addEventListener('install', function(event) { }.
  • Add Promise: After we install the service worker we will call the waitUntil() method. This function is a promise. So we will wait until the functions are finished running.
caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  • Set variable: then we will do some variable definitions to represent the files that we will cache.
  1. var CACHE_NAME = 'my-site-cache-v1';, We will name the cache according to what you want, but the cache name is recommended as follows 'my-site-cache-v1, So if later there are changes or additions you can add the version like 'my-site-cache-v1', 'my-site-cache-v2', 'my-site-cache-v3'. for more details we will do console.log () to see if change is open.

ezgif.com-video-to-gif (3).gif

We can see in the picture above, we have managed to cache my-site-cache-v1 and we can also see the file or directory file that we registered has been cached, so that when we reload our web page, we no longer need to pull the data we only need to use the cache.

  1. var urlsToCache =[], The second parameter is the URL or directory of the files that we will cache, We can define it in array form, in this tutorial, I have the CSS '/assets/main.css' , jQuery '/js/jquery.min.js' and the own javascript /js/main.js, that we will cache and don't forget to return those variable like this return cache.addAll(urlsToCache); and there are a few changes if previously written we use CDN, then I suggest you to download the jquery script and run it locally, so that we are easier to cache the jquery.

Change

<!DOCTYPE html>
<html>
<head>
    <title>PWA Aplication</title>
</head>
<body>
    <h1>Learn PWA from basics</h1>
    <div id="results"></div>
<script src="js/jquery.min.js"></script>
 <script type="text/javascript"src='js/main.js'></script>
</body>
</html>

Noted: to remember the file we cache in this section is a statism file, I suggest you separate dynamic and static files.

Activate Service worker

After the installation is complete we will enter the activate, part activate is the part that will be triggered when our web application page is closed, so we can use it when we want to replace or delete the old service worker with the latest.

sw.js

self.addEventListener('activate', function(event) {
  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.filter(function(cacheNames){
          return cacheNames != CACHE_NAME
        }).map(function(cacheName) {
            return caches.delete(cacheName)
        })
      );
    })
  );
});
  • Get list cache: We can get the cache key by using promise with the keys() method.

  • Filter cache: We will filter cache before we map, the goal is that we will clear the cache before if there is a new cache, because we will not save the old cache in memory. therefore we will do a filter like this cacheNames.filter(function(cacheNames){ }) and we will return the value in boolean return cacheNames != CACHE_NAME. CACHE_NAME is a variable that specifies the cache version that we have defined in the sw.js as follows var CACHE_NAME = 'my-site-cache-v1';.

  • Delete cache: then we will do the mapping to delete the cache as follows return caches.delete(cacheName).

Fetch cache

We have made a cache in the previous secton, but haven't actually used it, now we will learn how to use the cache using event fetch. This event is used to retrieve the value of the value in the stored cache, for more details we can see the following code.

sw.js

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});
  • Fecth event: We will use fetch event to retrieve data in the cache and in this event we no longer use waitUntil() but use respondWith()because we will give a respond.

  • Check cache: We will match and check whether the cache name already exists, We can see the cache at event.request, We can use promise with the match () method, and if the cache already exists. We will receive the response to the callback function parameter that is the response caches.match(event.request).then(function(response) {} and we return the response return response;. but if there is no cache we will fetch that's means we will use the network, So we will again access our web URL.

When we run our web automatically we have used the cache. If you have done the tutorial correctly, then we will be able to see the results as below. I would add a picture to see the difference.

  • Add image in index.html
<!DOCTYPE html>
<html>
<head>
    <title>PWA Aplication</title>
</head>
<body>
    <h1>Learn PWA from basics</h1>
    <img src="assets/woman.jpg" style="width:200px;">
    <div id="results"></div>
<script src="js/jquery.min.js"></script>
 <script type="text/javascript"src='js/main.js'></script>
</body>
</html>
  • Add files to cache
    I will add register for woman.jpg file to cache. we can see the results as shown
var urlsToCache = [
  '/',
  'assets/woman.jpg',
  'assets/main.css',
  'js/main.js',
  'js/jquery.min.js'
];

Screenshot_12.png

We have learned the cache in the service worker and learned a lot from it. I hope you can explore more about the cache in the service worker, there is a lot that we can do on the service worker and I will discuss it in the next tutorial, just this tutorial, hopefully it will be useful for you. thank you

Curricullum

Create base pwa app #1Introduction service worker and Web manifest

Proof of workdone

https://github.com/milleaduski/Pwa

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thank you for your contribution @duski.harahap.
We suggest the following points below:

  • We suggest that you put the keywords in the title of your tutorial, such as jQuery.

  • It's important to have comments in your code. The reader as you study your code will better understand what you are developing.

  • In your tutorial you can put the links like this:

<a href="https://github.com/jquery/jquery">jQuery</a>  


Thanks again for your good work on this tutorial.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

·

Thank you for your review, @portugalcoin!

So far this week you've reviewed 2 contributions. Keep up the good work!

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!