Skip to content

Latest commit

 

History

History
347 lines (271 loc) · 16.3 KB

ch2.asciidoc

File metadata and controls

347 lines (271 loc) · 16.3 KB

Grow with Google Challenge Notes: Chapter 2

2.1: Intro

We first meet our instructors: Jake Archibald from London who will do most of the teaching. Mike Wales from USA who gives us the quizzes. Jake goes on to show the importance of having offline first. He says that what we will be working on will work great on whatever type of connection. We will be working on the dev tools, IDB the in browser database, use user interface strategy to deal varying network conditions and updates.

2.2: The Problem

Jake talks about an app we will be working on. It’s not quite a progressive app yet, but what we will work on is to make it progressive. So what does progressive app mean?

Progressive app:
In 2015, designer Frances Berriman and Google Chrome engineer Alex Russell coined the term "Progressive Web Apps" [3] to describe apps taking advantage of new features supported by modern browsers, including service workers and web app manifests, that let users upgrade web apps to progressive web applications in their native operating system (OS). According to Google Developers,[3][4][5] these characteristics are:

Progressive - Work for every user, regardless of browser choice because they’re built with progressive enhancement as a core tenet.
Responsive - Fit any form factor: desktop, mobile, tablet, or forms yet to emerge.
Connectivity indepreplacementent - Service workers allow work offline, or on low quality networks.
App-like - Feel like an app to the user with app-style interactions and navigation.
Fresh - Always up-to-date thanks to the service worker update process.
Safe - Served via HTTPS to prevent snooping and ensure content hasn’t been tampered with.
Discoverable - Are identifiable as “applications” thanks to W3C manifests[6] and service worker registration scope allowing search engines to find them.
Re-engageable - Make re-engagement easy through features like push notifications.
Installable - Allow users to “keep” apps they find most useful on their home screen without the hassle of an app store.
Linkable - Easily shared via a URL and do not require complex installation.
Progressive Web Apps described by Shoaib in a follow-up post:[7] are an enhancement of existing web technology. As such, they do not require separate bundling or distribution. Publication of a Progressive Web App is as it would be for any other web page. As of 2017, Progressive Web Apps are supported by the Chrome browser, but more browsers may support the features needed in the future.

The technical baseline criteria for a site to be considered a Progressive Web App by browsers were described by Russell in a follow-up post:[8]

Originate from a Secure Origin. Served over TLS and green padlock displays (no active mixed content).
Load while offline (even if only a custom offline page). By implication, this means that Progressive Web Apps require Service Workers.
Reference a Web App Manifest with at least the four key properties: name, short_name, substr_url, and display (with a value of standalone or fullscreen)
An icon at least 144×144 large in png format. E.g.: "icons": [ \{ "src": "/images/icon-144.png", "sizes": "144x144", "type": "image/png" } ]

2.3: The Benefits of Offline First

Offline first means getting as much content as possible from the cache then the internet only if we can get content from the network.
If you do get content from the network, all new information will get stored into the cache. If you just can’t get content from the network, we just use what is in the cache. It might be outdated, but at least it’s better than nothing.

2.4: Quiz: What can Slow Us Down

Pretty much anything might slow down your connection. This page was pretty much stressing us the importance of offline first.

2.5: Quiz: What Does Online First Look Like

The quiz website is online first, so if the network is offline, it will pull something from the cache for fallback content or special page for offline.

In which of the following conditions will our app work well?
a. Good connection.
b. Bad connection.
c. Offline

Summary: Mike is mainly trying to tell you that offline first is better since online first will struggle horribly on bad connection type of networks. So the answers are A and C.

2.6: Quiz: What are Ways To Be Offline First

Which of these are offline first techniques?

a. Deliver the page’s header and content from a cache on the device, then attempt to fetch updated content from the network
b. Deliver the page’s header from the a cache, then attempt to fetch the content from the network.
c. attempt to fetch the page from the network, and if that fails, show cached content.
d. attempt to fetch the page from the network, if that fails, show an error page from a cache.

The answers are A and B because both of these attempt the cache before the network. The others are not because they require a wait from the network to succeed or fail thus not giving us the best performance if we were having network issues.

2.7: Introducing the Demo App

Jake shows us the app we will be customizing. We will be turning the app from online first to offline first. The app is called wittr

2.8: Quiz: Installing the Demo App

This section is mainly a to-do list to get the wittr app installed on your computer so you can be able to follow along+

1st step: install node.js because all the servers and build scripts are written in javascript.

2nd step: open up git bash, terminal, or command prompt and make sure you’re already on the directory you want all the files to be placed. To go to that directory just type cd directory
example:

cd C:\Users\username\Desktop

If you’re on windows and you have git, you can easily navigate to the actual folder and right click. You will see the option for git bash here to automatically have the bash selected for that directory.
screenshot

3rd step: Now that you’re on the right directory, clone the project to that folder. type:

git clone https://github.com/jakearchibald/wittr

Or if you have an ssh setup for github. You go here:

git clone [email protected]:jakearchibald/wittr.git

Summary: Install node.js and clone the project.

Note

Jake says if you want to learn git, there’s a free class: udacity class If you want a very quick one to teach you the basics in 15 minutes, I recommend Try Git. For this class, however, you don’t really need to know git. The only git commands you use for the lessons are:

git reset --hard   (for resetting the files)
git checkout branch-name (for getting the files to the proper state for that lesson)
Important
When using git reset --hard you need to check you’re in the correct directory. If you have other git folders and use git reset --hard, you’re not getting those edits after a commit back!

2.9: Quiz: Running the Demo app

Same as the previous lesson, here are the steps to continue on.

Step 1: After you’ve installed node.js and got the complete package of wittr, you’ll see your folder added a new folder called "wittr". Now you need to navigate to the wittr folder.

cd wittr

Step 2: Once inside the folder, you need npm or yarn to build the server. Either will work.

npm install

or

yarn install

This will fetch all the 3rd party code that is needed to run the app. note: There may be some errors and warnings for optional dependencies. Just ignore them.

Step 3: Once npm/yarn install is complete, you can start the server by typing:

npm run serv

or

yarn run serve
Important
From here on, you will always need to navigate to the wittr folder and type npm run serve or yarn run serve every single time when resuming the lesson. Once you type it, the console will let you know two servers are running: localhost:8888 and localhost:8889. If you ever need to restart or shut down the server, press ctrl c. If for whatever reason your server doesn’t start, shut down the server, and type git reset --hard into the console.
console1

Step 4: Now that the server is up and running, open up a browser and enter the address: localhost:8888. If you see the website, you’re done!

2.10: Exploring the Demo Apps Code

Jake explains that the app currently runs as online first
1st step: browser makes a request which goes via http-cache.
2nd step: If http-cache doesn’t have a match, it goes to the internet.
3rd step: internet will then send information to http-cache
fourth step: http-cache then sends the response to the browser.

Once those steps are fulfilled, we’ll have a website full of content. html, css, javascript, etc.
The javascript opens up a websocket that will continually stream data from the internet to the browser for any new updates.

The javascript files

In the class, we will be modifying the javascripts Index.js and IndexController.js. To navigate to the javascript file, it can be found in wittr > public > js > main

index.js is the starting point. It includes some polyfills, promises, and URL API that we will cover later on
indexController.js is where most of the magic happens.

Jake describes what the content inside the indexController does. They are the notes inside this code.

Warning
The code uses ECMAScript aka ES(5) and then used babel to translate(?). I’m not entirely certain what that all means, but once I do, hopefully I’ll edit this all out or just link to the clarification.
import PostsView from './views/Posts';
import ToastsView from './views/Toasts';
import idb from 'idb';

export default function IndexController(container) {
  this._container = container;
  this._postsView = new PostsView(this._container);
  this._toastsView = new ToastsView(this._container);
  this._lostConnectionToast = null;
  this._openSocket();
}

// open a connection to the server for live updates
IndexController.prototype._openSocket = function() {
  var indexController = this;
  var latestPostDate = this._postsView.getLatestPostDate();

  // create a url pointing to /updates with the ws protocol
  var socketUrl = new URL('/updates', window.location);
  socketUrl.protocol = 'ws';

  if (latestPostDate) {
    socketUrl.search = 'since=' + latestPostDate.valueOf();
  }

  // this is a little hack for the settings page's tests,
  // it isn't needed for Wittr
  socketUrl.search += '&' + location.search.slice(1);

  var ws = new WebSocket(socketUrl.href);

  // add listeners
  ws.addEventListener('open', function() {
    if (indexController._lostConnectionToast) {
      indexController._lostConnectionToast.hide();
    }
  });

  ws.addEventListener('message', function(event) {
    requestAnimationFrame(function() {
      indexController._onSocketMessage(event.data);
    });
  });

  ws.addEventListener('close', function() {
    // tell the user
    if (!indexController._lostConnectionToast) {
      indexController._lostConnectionToast = indexController._toastsView.show("Unable to connect. Retrying…");
    }

    // try and reconnect in 5 seconds
    setTimeout(function() {
      indexController._openSocket();
    }, 5000);
  });
};

// called when the web socket sends message data
IndexController.prototype._onSocketMessage = function(data) {
  var messages = JSON.parse(data);
  this._postsView.addPosts(messages);
};

The two servers

localhost:8888 is the actual website that we can view the changes.
localhost:8889 has the options to control 8888’s atmosphere. You can imitate perfect internet, slow internet, liefi, and offline. At the bottom there’s test results to see if you passed the test by inserting the proper test ID.

2.11: Quiz: Changing Connection Types

In this little lesson, they want you to play around with localhost:8889’s features.

Test 1:
Step 1: While you’re on the control website, localhost:8889 make sure you select perfect
Step 2: In the Test ID, enter the text: demo
Step 3: You should see the result: "Yep, the demo’s working".

Test 2:
Step 1: While you’re still in the control page, refresh the page and select "offline" instead of perfect.
Step 2: Head over to the app webpage at localhost:8888 and refresh the page. There should be a blank webpage.
Step 3: Head back over to the control site and type: offline into the test ID.
Step 4: You should see a message: "Yep! The server is totally dead!"

2.12: Quiz: Testing Lie Fi Mode

Same as the previous lesson.
Step 1: Instead of selecting perfect or offline, select Lie-fi.
Step 2: In the Test ID, insert lie-fi.
Step 3: You should see the result: "Yeeeep, that’s lie-fi alright."
Step 4: Go to the app website, refresh, and get angry.

2.13: Introducing Service Worker

Service worker helps you control the network. What exactly IS a service worker?

A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction. Today, they already include features like push notifications and background sync. In the future, service workers will support other things like periodic sync or geofencing. The core feature discussed in this tutorial is the ability to intercept and handle network requests, including programmatically managing a cache of responses.

The reason this is such an exciting API is that it allows you to support offline experiences, giving developers complete control over the experience.

Before service worker, there was one other API that gave users an offline experience on the web called AppCache. There are a number of issues with the AppCache API that service workers were designed to avoid.

Things to note about a service worker:

It’s a JavaScript Worker, so it can’t access the DOM directly. Instead, a service worker can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM if needed. Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled. It’s terminated when not in use, and restarted when it’s next needed, so you cannot rely on global state within a service worker’s onfetch and onmessage handlers. If there is information that you need to persist and reuse across restarts, service workers do have access to the IndexedDB API. Service workers make extensive use of promises, so if you’re new to promises, then you should stop reading this and check out Promises, an introduction.