Alfie Mellor

Alfie Mellor

1562558947

A Beginner's Guide to Workbox For Webpack

In this codelab, you use Workbox to make a simple web app work offline.

If you’d like a conceptual overview of Workbox before starting this tutorial, see the overview.

Step 1: Set up your project

The project that you’re going to add Workbox to is hosted on Glitch. First, you need to set up Glitch so that you can edit your own copy of the project.

1 - Open the demo.

2 - Figure 1. The starting point demo, hosted on Glitch

3 - Click workbox-webpack at the top-left of the page. The Project info and options dropdown appears.

4 - Click Remix This. Your browser redirects to an editable copy of the project.

Try out the initial app

The client-side JavaScript in the app fetches the top 10 Hacker News (HN) articles, and then populates the HTML with the content.

Note: This tutorial uses Google Chrome and Chrome DevTools to demonstrate how the web app behaves when offline. You can use any browser that supports service workers.

1- Click Show. The live app appears in a new tab.

Figure 2. The live appIn the tab that’s running the live app, press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux) to open DevTools.

2 - In the tab that’s running the live app, press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux) to open DevTools.

3 - Focus DevTools and press Command+Shift+P (Mac) or Control+Shift+P (Windows, Linux) to open the Command Menu.

4 - Type Offline, select Go offline, then press Enter. Google Chrome now has no connection to the Internet in this tab.

Figure 3. The Go Offline command

5 - Reload the page. Google Chrome says that you’re offline. In other words, the app doesn’t work at all when offline.

Figure 4. The initial app doesn’t work at all when offline

6 - Open the Command Menu again, type Online, and select Go online to restore your internet connection in this tab.

Step 2: Install Workbox

Next, you’re going to add Workbox to the project to enable an offline experience.

  1. Re-focus the tab that shows you the source code of the project.
  2. Click package.json to open that file.
  3. Click Add package.
  4. Type workbox-webpack-plugin within the Add Package text box, then click on the matching package to add it to the project.
  5. Note: This is equivalent to running npm install workbox-webpack-plugin. In your own projects, you’ll probably want to save Workbox as a development dependency instead by running npm install workbox-webpack-plugin --save-dev, since workbox-webpack-plugin is a build-time tool.

Figure 5. Adding the workbox-webpack-plugin package

Every time you make a change to your code, Glitch automatically re-builds and re-deploys your app. The tab running the live app automatically refreshes, too.

Step 3: Add Workbox to your Webpack build process

Workbox is installed, but you’re not using it in your webpack build process, yet.

1 - Click webpack.config.js to open that file.

2 - Import the Workbox plugin. The bold code is the code that you need to add to your project.

const path = require('path'),
    htmlPlugin = require('html-webpack-plugin'),
    cleanPlugin = require('clean-webpack-plugin'),
    dist = 'dist',
    workboxPlugin = require('workbox-webpack-plugin');

3 - Call the Workbox plugin as the last step in plugins.

plugins: [
  new cleanPlugin([dist]),
  new htmlPlugin({
    filename: 'index.html',
    title: 'Get Started With Workbox For Webpack'
  }),
  new workboxPlugin.GenerateSW({
    swDest: 'sw.js',
    clientsClaim: true,
    skipWaiting: true,
  })
]

Optional: How the config works

webpack.config.js determines how the app is built.

  • cleanPlugin deletes dist, which is the path to the output directory.
  • htmlPlugin re-generates the HTML output and places it back in dist.
  • workboxPlugin.GenerateSW knows about the assets bundled by webpack, and generates service worker code for caching those files. Since Workbox revisions each file based on its contents, Workbox should always be the last plugin you call.

The object that you pass to workboxPlugin.GenerateSW configures how Workbox runs.

  • swDest is where Workbox outputs the service worker that it generates. The parent directory for this file will be based on your output.path webpack configuration.
  • clientsClaim instructs the latest service worker to take control of all clients as soon as it’s activated. See clients.claim.
  • skipWaiting instructs the latest service worker to activate as soon as it enters the waiting phase. See Skip the waiting phase.

Step 4: Register and inspect the generated service worker

Workbox has generated a service worker, but there’s no reference to it from your app, yet.

1 - Click src/app.js to open that file.

2 - Register your service worker at the bottom of init().

function init() {
  ...
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/sw.js').then(registration => {
        console.log('SW registered: ', registration);
      }).catch(registrationError => {
        console.log('SW registration failed: ', registrationError);
      });
    });
  }
}

3 - Re-focus the tab that’s running the live version of your app. In the DevTools Console you see a message indicating that the service worker was registered.

4 - Click the Application tab of DevTools.

5 - Click the Service Workers tab.

Figure 6. The Service Workers pane

6 - Click sw.js, next to Source. DevTools displays the service worker code that Workbox generated. It should look close to this:

Figure 7. The generated service worker code

Try out the offline-capable app

Your app now sort-of works offline. Try it now:

1 - In the live version of your app, use DevTools to go offline again. Focus DevTools and press Command+Shift+P (Mac) or Control+Shift+P (Windows, Linux) to open the Command Menu. Type Offline, select Go offline, then press Enter.

2 - Reload the page. The title of the page appears, but the list of the top 10 stories doesn’t.

3 - Click the Network tab in DevTools. The request for topstories.json is red, meaning that it failed. This is why the list isn’t appearing. The app tries to make a request for <a href="https://hacker-news.firebaseio.com/v0/topstories.json" target="_blank">https://hacker-news.firebaseio.com/v0/topstories.json</a>, but the request fails since you’re offline and you haven’t instructed Workbox to cache this resource, yet.

Figure 8. The incomplete offline experience

4 - Use the Command Menu in DevTools to go back online.

Optional: How the service worker code works

The service worker code is generated based on your Workbox configuration.

  • importScripts('<a href="https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');" target="_blank">https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');</a> imports Workbox’s service worker library. You can inspect this file from the Sources panel of DevTools.

Figure 9. The code for Workbox’s service worker library

  • The self.__precacheManifest array lists all of the resources that Workbox is precaching.
  • Each resource has a revision property. This is how Workbox determines when to update a resource. Each time you build your app, Workbox generates a hash based on the contents of the resource. If the contents change, then the revision hash changes.
  • When the service worker runs, it writes the url and revision of each resource to IndexedDB (IDB) if it doesn’t exist. If the resource does exist, the service worker checks that the revision in its code matches the revision in IDB. If the hashes don’t match, then the resource has changed, and therefore the service worker needs to download the updated resource and update the hash in IDB.

In sum, Workbox only re-downloads resources when they change, and ensures that your app always caches the most up-to-date version of each resource.

Step 5: Add runtime caching

Runtime caching lets you store content that’s not under your control when your app requests it at runtime. For example, by runtime caching the Hacker News content which this app relies on, you’ll be able to provide an improved offline experience for your users. When users visit the app while offline, they’ll be able to see the content from the last time that they had an internet connection.

  1. Re-focus the tab that shows you the source code of your project.
  2. Open webpack.config.js again.
  3. Add a runtimeCaching property to your Workbox configuration. urlPattern is a regular expression pattern telling Workbox which URLs to store locally. (When your app makes a network request at runtime, Workbox caches any request that matches the regular expression in <em>handler</em>, regardless of its origin. This means that you can cache content from external sites as well, as this example demonstrates.) handler defines the caching strategy that Workbox uses for any matching URL. See The Offline Cookbook for more on caching strategies.
new workboxPlugin.GenerateSW({
  swDest: 'sw.js',
  clientsClaim: true,
  skipWaiting: true,
  runtimeCaching: [{
    urlPattern: new RegExp('https://hacker-news.firebaseio.com'),
    handler: 'StaleWhileRevalidate'
  }]
})

Try out the complete offline experience

The app now provides a complete offline experience. Try it now:

1 - Reload the live version of your app.

2 - Use the DevTools Command Menu to go back offline.

3 - Reload the app. The app now displays the content from the last time that you were online. If you’re still only seeing the page title, go back online, reload the page, and then try again.

Figure 10. The complete offline experience

4 - Use the DevTools Command Menu to go back online.

Step 6: Create your own service worker

Up until now, you’ve been letting Workbox generate your entire service worker. If you’ve got a big project, or you want to customize how you cache certain resources, or do custom logic in your service worker, then you need to create a custom service worker that calls Workbox instead. Think of the service worker code you write as a template. You write your custom logic with placeholder keywords that instruct Workbox where to inject its code.

In this section, you add push notification support in your service worker. Since this is custom logic, you need to write custom service worker code, and then inject the Workbox code into the service worker at build-time.

1 - Re-focus the tab containing your project source code.

2 - Add the following line of code to the init() function in app.js.

function init() {
  ...
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/sw.js').then(registration => {
        console.log('SW registered: ', registration);
        registration.pushManager.subscribe({userVisibleOnly: true});
      }).catch(registrationError => {
        ...
      });
    });
  }
}

Warning: For simplicity, this demo asks for permission to send push notifications as soon as the service worker is registered. Best practices strongly recommend against out-of-context permission requests like this in real apps. See [Permission UX][UX].

3 - Click New File, enter src/sw.js, then press Enter.

4 - Add the following code to src/sw.js.

workbox.core.skipWaiting();
workbox.core.clientsClaim();

workbox.routing.registerRoute(
  new RegExp('https://hacker-news.firebaseio.com'),
  new workbox.strategies.StaleWhileRevalidate()
);

self.addEventListener('push', (event) => {
  const title = 'Get Started With Workbox';
  const options = {
    body: event.data.text()
  };
  event.waitUntil(self.registration.showNotification(title, options));
});

workbox.precaching.precacheAndRoute(self.__precacheManifest);

Important: workbox.precaching.precacheAndRoute(self.__precacheManifest) reads a list of URLs to precache from an externally defined variable, self.__precacheManifest. At build-time, Workbox injects code needed set self.__precacheManifest to the correct list of URLs.

5 - Open webpack.config.json.

6 - Remove the runtimeCaching, clientsClaim, and skipWaiting properties from your Workbox plugin configuration. These are now handled in your service worker code.

7 - Change the GenerateSW to InjectManifest and add the swSrc property to instruct Workbox to inject its code into a custom service worker.

new workboxPlugin.InjectManifest({
  swSrc: './src/sw.js',
  swDest: 'sw.js'
})

Try out push notifications

The app is now all set to handle push notifications. Try it now:

  1. Re-focus the tab running the live version of your app.
  2. Click Allow when Chrome asks you if you want to grant the app permission to send push notifications.
  3. Go to back to the Service Workers tab in DevTools.
  4. Enter some text into the Push text box, then click Push. Your operating system displays a push notification from the app.

Figure 11. Simulating a push notification from DevTools

Note: If you don’t see the Push text box, you’re running an older version of Chrome. Click the Push link instead. DevTools sends a notification with the text Test push message from DevTools.

Optional: How service worker injection works

At the bottom of your custom service worker, you call workbox.precaching.precacheAndRoute([]);. This is a placeholder. At build-time, the Workbox plugin replaces the empty array with the list of resources to precache. Your Workbox build configuration still determines what resources get precached.

#webpack #web-development

What is GEEK

Buddha Community

A Beginner's Guide to Workbox For Webpack
Tia  Gottlieb

Tia Gottlieb

1596336480

Beginners Guide to Machine Learning on GCP

Introduction to Machine Learning

  • Machine Learning is a way to use some set of algorithms to derive predictive analytics from data. It is different than Business Intelligence and Data Analytics in a sense that In BI and Data analytics Businesses make decision based on historical data, but In case of Machine Learning , Businesses predict the future based on the historical data. Example, It’s a difference between what happened to the business vs what will happen to the business.Its like making BI much smarter and scalable so that it can predict future rather than just showing the state of the business.
  • **ML is based on Standard algorithms which are used to create use case specific model based on the data **. For example we can build the model to predict delivery time of the food, or we can build the model to predict the Delinquency rate in Finance business , but to build these model algorithm might be similar but the training would be different.Model training requires tones of examples (data).
  • Basically you train your standard algorithm with your Input data. So algorithms are always same but trained models are different based on use cases. Your trained model will be as good as your data.

ML, AI , Deep learning ? What is the difference?

Image for post

ML is type of AI

AI is a discipline , Machine Learning is tool set to achieve AI. DL is type of ML when data is unstructured like image, speech , video etc.

Barrier to Entry Has Fallen

AI & ML was daunting and with high barrier to entry until cloud become more robust and natural AI platform. Entry barrier to AI & ML has fallen significantly due to

  • Increasing availability in data (big data).
  • Increase in sophistication in algorithm.
  • And availability of hardware and software due to cloud computing.

GCP Machine Learning Spectrum

Image for post

  • For Data scientist and ML experts , TensorFlow on AI platform is more natural choice since they will build their own custom ML models.
  • But for the users who are not experts will potentially use Cloud AutoML or Pre-trained ready to go model.
  • In case of AutoML we can trained our custom model with Google taking care of much of the operational tasks.
  • Pre-trained models are the one which are already trained with tones of data and ready to be used by users to predict on their test data.

Prebuilt ML Models (No ML Expertise Needed)

  • As discuss earlier , GCP has lot of Prebuilt models that are ready to use to solve common ML task . Such as image classification, Sentiment analysis.
  • Most of the businesses are having many unstructured data sources such as e-mail, logs, web pages, ppt, documents, chat, comments etc.( 90% or more as per various studies)
  • Now to process these unstructured data in the form of text, we should use Cloud Natural Language API.
  • Similarly For common ML problems in the form of speech, video, vision we should use respective Prebuilt models.

#ml-guide-on-gcp #ml-for-beginners-on-gcp #beginner-ml-guide-on-gcp #machine-learning #machine-learning-gcp #deep learning

Abigail betty

Abigail betty

1624226400

What is Bitcoin Cash? - A Beginner’s Guide

Bitcoin Cash was created as a result of a hard fork in the Bitcoin network. The Bitcoin Cash network supports a larger block size than Bitcoin (currently 32mb as opposed to Bitcoin’s 1mb).

Later on, Bitcoin Cash forked into Bitcoin SV due to differences in how to carry on its developments.

That’s Bitcoin Cash in a nutshell. If you want a more detailed review watch the complete video. Here’s what I’ll cover:

0:50 - Bitcoin forks
2:06 - Bitcoin’s block size debate
3:35 - Big blocks camp
4:26 - Small blocks camp
5:16 - Small blocks vs. big blocks arguments
7:05 - How decisions are made in the Bitcoin network
10:14 - Block size debate resolution
11:06 - Bitcoin cash intro
11:28 - BTC vs. BCH
12:13 - Bitcoin Cash (ABC) vs. Bitcoin SV
13:09 - Conclusion
📺 The video in this post was made by 99Bitcoins
The origin of the article: https://www.youtube.com/watch?v=ONhbb4YVRLM
🔺 DISCLAIMER: The article is for information sharing. The content of this video is solely the opinions of the speaker who is not a licensed financial advisor or registered investment advisor. Not investment advice or legal advice.
Cryptocurrency trading is VERY risky. Make sure you understand these risks and that you are responsible for what you do with your money
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#bitcoin #blockchain #bitcoin cash #what is bitcoin cash? - a beginner’s guide #what is bitcoin cash #a beginner’s guide

A Beginner’s Guide to Setting Up a Web Application with Typescript and Express

Web applications are types of software applications that run on remote servers (source). Examples of web applications can range from word processors, to file scanners, video editing tools, shopping carts, and more. Web applications can be great additions to any website; they can even function as websites themselves (Facebook, Gmail, and Udacity’s classroom are all examples of popular web applications), so understanding how to set up and implement a web application is a fantastic skill to have.

For this guide, I am assuming that you already have a basic knowledge of npmnode and whatExpress Requests and Responses are (or that you at least know what they are used for in their basic sense). Also, I assume that you know what the npm install and mkdir commands do. You have to know basic Typescript to implement — or at least know basic JavaScript to read and understand — the code below. Finally, this is the base for the backend of a web application. You still need to create a frontend application using a framework like Angular or an HTML/CSS file to make requests and display responses.

Before you start, it’s important that you create a folder in your favorite place on your computer. This can be anywhere as long as you have a sense of how you are going to find it later when you come up with an awesome project to start developing.

The Process:

Image for post

#web-development #backend #software-development #beginners-guide #beginner

Alfie Mellor

Alfie Mellor

1562558947

A Beginner's Guide to Workbox For Webpack

In this codelab, you use Workbox to make a simple web app work offline.

If you’d like a conceptual overview of Workbox before starting this tutorial, see the overview.

Step 1: Set up your project

The project that you’re going to add Workbox to is hosted on Glitch. First, you need to set up Glitch so that you can edit your own copy of the project.

1 - Open the demo.

2 - Figure 1. The starting point demo, hosted on Glitch

3 - Click workbox-webpack at the top-left of the page. The Project info and options dropdown appears.

4 - Click Remix This. Your browser redirects to an editable copy of the project.

Try out the initial app

The client-side JavaScript in the app fetches the top 10 Hacker News (HN) articles, and then populates the HTML with the content.

Note: This tutorial uses Google Chrome and Chrome DevTools to demonstrate how the web app behaves when offline. You can use any browser that supports service workers.

1- Click Show. The live app appears in a new tab.

Figure 2. The live appIn the tab that’s running the live app, press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux) to open DevTools.

2 - In the tab that’s running the live app, press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux) to open DevTools.

3 - Focus DevTools and press Command+Shift+P (Mac) or Control+Shift+P (Windows, Linux) to open the Command Menu.

4 - Type Offline, select Go offline, then press Enter. Google Chrome now has no connection to the Internet in this tab.

Figure 3. The Go Offline command

5 - Reload the page. Google Chrome says that you’re offline. In other words, the app doesn’t work at all when offline.

Figure 4. The initial app doesn’t work at all when offline

6 - Open the Command Menu again, type Online, and select Go online to restore your internet connection in this tab.

Step 2: Install Workbox

Next, you’re going to add Workbox to the project to enable an offline experience.

  1. Re-focus the tab that shows you the source code of the project.
  2. Click package.json to open that file.
  3. Click Add package.
  4. Type workbox-webpack-plugin within the Add Package text box, then click on the matching package to add it to the project.
  5. Note: This is equivalent to running npm install workbox-webpack-plugin. In your own projects, you’ll probably want to save Workbox as a development dependency instead by running npm install workbox-webpack-plugin --save-dev, since workbox-webpack-plugin is a build-time tool.

Figure 5. Adding the workbox-webpack-plugin package

Every time you make a change to your code, Glitch automatically re-builds and re-deploys your app. The tab running the live app automatically refreshes, too.

Step 3: Add Workbox to your Webpack build process

Workbox is installed, but you’re not using it in your webpack build process, yet.

1 - Click webpack.config.js to open that file.

2 - Import the Workbox plugin. The bold code is the code that you need to add to your project.

const path = require('path'),
    htmlPlugin = require('html-webpack-plugin'),
    cleanPlugin = require('clean-webpack-plugin'),
    dist = 'dist',
    workboxPlugin = require('workbox-webpack-plugin');

3 - Call the Workbox plugin as the last step in plugins.

plugins: [
  new cleanPlugin([dist]),
  new htmlPlugin({
    filename: 'index.html',
    title: 'Get Started With Workbox For Webpack'
  }),
  new workboxPlugin.GenerateSW({
    swDest: 'sw.js',
    clientsClaim: true,
    skipWaiting: true,
  })
]

Optional: How the config works

webpack.config.js determines how the app is built.

  • cleanPlugin deletes dist, which is the path to the output directory.
  • htmlPlugin re-generates the HTML output and places it back in dist.
  • workboxPlugin.GenerateSW knows about the assets bundled by webpack, and generates service worker code for caching those files. Since Workbox revisions each file based on its contents, Workbox should always be the last plugin you call.

The object that you pass to workboxPlugin.GenerateSW configures how Workbox runs.

  • swDest is where Workbox outputs the service worker that it generates. The parent directory for this file will be based on your output.path webpack configuration.
  • clientsClaim instructs the latest service worker to take control of all clients as soon as it’s activated. See clients.claim.
  • skipWaiting instructs the latest service worker to activate as soon as it enters the waiting phase. See Skip the waiting phase.

Step 4: Register and inspect the generated service worker

Workbox has generated a service worker, but there’s no reference to it from your app, yet.

1 - Click src/app.js to open that file.

2 - Register your service worker at the bottom of init().

function init() {
  ...
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/sw.js').then(registration => {
        console.log('SW registered: ', registration);
      }).catch(registrationError => {
        console.log('SW registration failed: ', registrationError);
      });
    });
  }
}

3 - Re-focus the tab that’s running the live version of your app. In the DevTools Console you see a message indicating that the service worker was registered.

4 - Click the Application tab of DevTools.

5 - Click the Service Workers tab.

Figure 6. The Service Workers pane

6 - Click sw.js, next to Source. DevTools displays the service worker code that Workbox generated. It should look close to this:

Figure 7. The generated service worker code

Try out the offline-capable app

Your app now sort-of works offline. Try it now:

1 - In the live version of your app, use DevTools to go offline again. Focus DevTools and press Command+Shift+P (Mac) or Control+Shift+P (Windows, Linux) to open the Command Menu. Type Offline, select Go offline, then press Enter.

2 - Reload the page. The title of the page appears, but the list of the top 10 stories doesn’t.

3 - Click the Network tab in DevTools. The request for topstories.json is red, meaning that it failed. This is why the list isn’t appearing. The app tries to make a request for <a href="https://hacker-news.firebaseio.com/v0/topstories.json" target="_blank">https://hacker-news.firebaseio.com/v0/topstories.json</a>, but the request fails since you’re offline and you haven’t instructed Workbox to cache this resource, yet.

Figure 8. The incomplete offline experience

4 - Use the Command Menu in DevTools to go back online.

Optional: How the service worker code works

The service worker code is generated based on your Workbox configuration.

  • importScripts('<a href="https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');" target="_blank">https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');</a> imports Workbox’s service worker library. You can inspect this file from the Sources panel of DevTools.

Figure 9. The code for Workbox’s service worker library

  • The self.__precacheManifest array lists all of the resources that Workbox is precaching.
  • Each resource has a revision property. This is how Workbox determines when to update a resource. Each time you build your app, Workbox generates a hash based on the contents of the resource. If the contents change, then the revision hash changes.
  • When the service worker runs, it writes the url and revision of each resource to IndexedDB (IDB) if it doesn’t exist. If the resource does exist, the service worker checks that the revision in its code matches the revision in IDB. If the hashes don’t match, then the resource has changed, and therefore the service worker needs to download the updated resource and update the hash in IDB.

In sum, Workbox only re-downloads resources when they change, and ensures that your app always caches the most up-to-date version of each resource.

Step 5: Add runtime caching

Runtime caching lets you store content that’s not under your control when your app requests it at runtime. For example, by runtime caching the Hacker News content which this app relies on, you’ll be able to provide an improved offline experience for your users. When users visit the app while offline, they’ll be able to see the content from the last time that they had an internet connection.

  1. Re-focus the tab that shows you the source code of your project.
  2. Open webpack.config.js again.
  3. Add a runtimeCaching property to your Workbox configuration. urlPattern is a regular expression pattern telling Workbox which URLs to store locally. (When your app makes a network request at runtime, Workbox caches any request that matches the regular expression in <em>handler</em>, regardless of its origin. This means that you can cache content from external sites as well, as this example demonstrates.) handler defines the caching strategy that Workbox uses for any matching URL. See The Offline Cookbook for more on caching strategies.
new workboxPlugin.GenerateSW({
  swDest: 'sw.js',
  clientsClaim: true,
  skipWaiting: true,
  runtimeCaching: [{
    urlPattern: new RegExp('https://hacker-news.firebaseio.com'),
    handler: 'StaleWhileRevalidate'
  }]
})

Try out the complete offline experience

The app now provides a complete offline experience. Try it now:

1 - Reload the live version of your app.

2 - Use the DevTools Command Menu to go back offline.

3 - Reload the app. The app now displays the content from the last time that you were online. If you’re still only seeing the page title, go back online, reload the page, and then try again.

Figure 10. The complete offline experience

4 - Use the DevTools Command Menu to go back online.

Step 6: Create your own service worker

Up until now, you’ve been letting Workbox generate your entire service worker. If you’ve got a big project, or you want to customize how you cache certain resources, or do custom logic in your service worker, then you need to create a custom service worker that calls Workbox instead. Think of the service worker code you write as a template. You write your custom logic with placeholder keywords that instruct Workbox where to inject its code.

In this section, you add push notification support in your service worker. Since this is custom logic, you need to write custom service worker code, and then inject the Workbox code into the service worker at build-time.

1 - Re-focus the tab containing your project source code.

2 - Add the following line of code to the init() function in app.js.

function init() {
  ...
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/sw.js').then(registration => {
        console.log('SW registered: ', registration);
        registration.pushManager.subscribe({userVisibleOnly: true});
      }).catch(registrationError => {
        ...
      });
    });
  }
}

Warning: For simplicity, this demo asks for permission to send push notifications as soon as the service worker is registered. Best practices strongly recommend against out-of-context permission requests like this in real apps. See [Permission UX][UX].

3 - Click New File, enter src/sw.js, then press Enter.

4 - Add the following code to src/sw.js.

workbox.core.skipWaiting();
workbox.core.clientsClaim();

workbox.routing.registerRoute(
  new RegExp('https://hacker-news.firebaseio.com'),
  new workbox.strategies.StaleWhileRevalidate()
);

self.addEventListener('push', (event) => {
  const title = 'Get Started With Workbox';
  const options = {
    body: event.data.text()
  };
  event.waitUntil(self.registration.showNotification(title, options));
});

workbox.precaching.precacheAndRoute(self.__precacheManifest);

Important: workbox.precaching.precacheAndRoute(self.__precacheManifest) reads a list of URLs to precache from an externally defined variable, self.__precacheManifest. At build-time, Workbox injects code needed set self.__precacheManifest to the correct list of URLs.

5 - Open webpack.config.json.

6 - Remove the runtimeCaching, clientsClaim, and skipWaiting properties from your Workbox plugin configuration. These are now handled in your service worker code.

7 - Change the GenerateSW to InjectManifest and add the swSrc property to instruct Workbox to inject its code into a custom service worker.

new workboxPlugin.InjectManifest({
  swSrc: './src/sw.js',
  swDest: 'sw.js'
})

Try out push notifications

The app is now all set to handle push notifications. Try it now:

  1. Re-focus the tab running the live version of your app.
  2. Click Allow when Chrome asks you if you want to grant the app permission to send push notifications.
  3. Go to back to the Service Workers tab in DevTools.
  4. Enter some text into the Push text box, then click Push. Your operating system displays a push notification from the app.

Figure 11. Simulating a push notification from DevTools

Note: If you don’t see the Push text box, you’re running an older version of Chrome. Click the Push link instead. DevTools sends a notification with the text Test push message from DevTools.

Optional: How service worker injection works

At the bottom of your custom service worker, you call workbox.precaching.precacheAndRoute([]);. This is a placeholder. At build-time, the Workbox plugin replaces the empty array with the list of resources to precache. Your Workbox build configuration still determines what resources get precached.

#webpack #web-development

Alverta  Crist

Alverta Crist

1598286933

The Ultimate React Guide For Beginners In 2020.

The Ultimate React Guide For Beginners In 2020. By Caspar Camille Rubin on Unsplash. React is a JavaScript library created by Facebook and is a great tool for building UI components.

#programming #javascript #guides-and-tutorials #tech #beginners-guide