Progressive Web Applications and an Offline First Mentality
Omer Goldberg · Reversim Summit 2018 transcripts · Markdown
Machine transcript. It can contain errors. Click a time to play the video from that point.
00:11 Hi everyone, good morning. I'm Omer Goldberg, I'm a software engineer at Facebook. And today I'm really excited to talk to you about Progressive Web Apps. Now the reason I'm excited to talk about Progressive Web Apps is because the line between what is a native application and what is the website is becoming blurrier and blurrier every single day. With newer APIs, we now have access to features that were only once available in native applications, features such as push notifications, easily adding an icon for your website to the user's home screen, and much more. New technology isn't the only thing that's exciting here. There's actually a pretty interesting business case. Last year Google published these findings where we see that they're comparing the top 1,000 mobile websites and the top 1,000 mobile apps when we're looking at monthly unique visitors. And what we see here is that there's almost three times as many monthly unique visitors in mobile websites versus mobile applications. So if this is the case, why do even bother building native applications at all?
01:12 Well, the answer is here and it's when we talk about engagement. Engagement on native applications is nearly 20 times larger than engagement on mobile websites. Luckily for us though, Web UX is rapidly improving. Within with the introduction of new technologies, mobile websites can now become faster, more reliable, and more engaging than ever before. Now, this is working so well that it's rapidly being adopted by industry leaders, such as Facebook, Twitter, Google, which of course is one of the main drivers behind this technology, as well as Forbes. Let's look at a quick study of what progressive moving from native applications to Progressive Web Apps has done for Forbes. With the internet access of the web there's no place that I can't reach. The impact of the web on the news room was monumental. It's now more the reader telling the news room, "This is important to me."
02:12 You really have to start to build from scratch what is a story on the phone. With a progressive web app, there's a link. Tap it, install it with no friction. The PWA is on their phone, done. And once that is installed, we are able to alert you to, "Hey, we got some more information for you." If you're interested in whatever areas that you are, you can install that subject, that topic and we're going to serve you the content that you want. And that's going to change our business in a big way. The technology has enabled us to make our new PWA faster than our current mobile site. We're now able to deliver visuals faster. And if you can start to deliver visuals faster, then you can start to change the formats you do. People are willing to stay longer. If they stay longer, they see more advertising. The PWA is going to result in more personalization. Personalization will yield more engagement.
03:14 The web has made me realize there's an audience out there, and there's an audience that's knowledgeable, and there's an audience that needs to be understood. So the numbers speak for themselves. After moving from a mobile website to a PWA, Forbes has seen a huge increase in the length of the user sessions, which in turn has increased time spent, the amount of ads they see, and revenue. So the business case here is pretty clear. Users are already visiting mobile websites in staggering numbers. With new technologies, we can create better experiences which take users who were previously just browsing and help us retain them on a day-to-day basis. Now, before we jump in and dive into the tech, it's important for me to emphasize this. PWA is non-binary. It's not that you either have a progressive web app or that you don't. When we're talking about PWA, we're talking about a suite of new web APIs. So, depending on your business case, you can decide to adopt all of them or some of them, depending on what you need.
04:17 Today, we're going to talk about four subjects. We're going to talk about how do you take your mobile website and get the browser to prompt the user to install it. I'm saying installation even though it's 0 megabytes installation. Afterwards, we're going to talk about service workers, which are the core technology that enable us access to many of the APIs in PWA. After that, we're going to talk about how can we use a service worker as a network proxy, as well as talk to the cache API. And lastly, we're going to talk on the web push API. So, let's go for an easy win and see how we convert our mobile website easily into something that has an icon on the user's home screen. Now, in order to get prompted by the browser to install the app, we're going to need to do three things. Now, after we do the installation, everything at the end we're going to have here an icon, which looks exactly like every native app icon. For the most part, the user won't be won't be able to tell the difference if we're doing a good job. And when the user launches, you get the whole full screen.
05:21 This is designed like a mobile website, but if you did it like an app, many use cases the user shouldn't be able to tell the difference. So how do we get that icon on the home screen? So, there is a way to explicitly install it from the browser. But what's really cool and pretty new on the web is that the browser will actually prompt your users to install the app. Now, when does this prompt happen? So this is something that's still currently under development. The current heuristic by Google is if they see that the user is on your website for more than 30 seconds and your website is a progressive web app, it's going to prompt them to install it and add it to their home screen like this. Now, how do we get that prompt? So, we need three things in order for the browser to prompt our users to install the app. The first is a web manifest. So, if you've ever developed something like a Chrome extension, it's exactly the same. It's just a bunch of metadata that we need to provide for the browser for it to recognize our website as a PWA, and and give us access to extra features. In addition to the manifest, our website has to be served over https.
06:24 And lastly, we need to register a service worker. All right, so let's take a look at the manifest.json file. In a second, we're going to look at all the values in depth. But at first, it's important to let the browser know that we have an index manifest.json file. So just in the entry point to your application, just point to your manifest.json and then we can get started. Now, let's take a deeper look at the manifest.json. Now, the first field you're going to notice is the display field. Now, the display field has several different values, and it determines how the user is going to see our application once it's launched from the home screen. Now, in this example today, I'm using standalone. What standalone does is that it captures all of the real estate on the user's home screen, except for the status bar at the top. So, you're going to have all the real estate, except where the user can see things like WhatsApp messages, signal strength, etc. Now, you can specify different things. If you want all the real estate, including the status bar, which is good for things like mobile gaming, specify max and then you'll capture everything.
07:26 There are other values such as a browser, which will give you the normal UI that you're used to with the browser URL bar at the top. All right, now we have the name and short name. So, since this application is going to be on the user's home screen and can be accessed from different settings and preferences, we get to provide two different names. Now, the OS is already going to decide for us when it's going to display either the name or the short name, and this is heavily dependent on the real estate. Okay? So, if it's something like on the home screen where you don't have a lot of room for your icon, it's going to probably opt to show the short name. If it's something like an app preferences or settings, it might show the full name. It depends on the length of the name you provide. It's best to provide both. Now, we're going to talk about icons. So, what's mandatory for for icons is that you provide two sizes. The first is 192 and 192, and the second is 512 by 512. Now, if you want a crisper icon look, you're welcome to add icons in increments of 40 pixels starting from 192 till 512.
08:28 In these cases, the OS will already decide which when to show which icon for the best experience for the user. And the background color. So, the background color is important for one thing that we're used to from native apps. This is a splash screen. So, in contrast to regular browsers, when an app is loading and you might just see like a blank screen or maybe a spinner, here we get the splash screen that we're all used to seeing in native apps. And it looks something like this. So, we could tap on the the PWA icon, and while the website is loading, we get the splash screen. Of course, you can customize it a lot more than this, but it's pretty cool because we get it out of the box just by providing that manifest JSON with a background color, icon, and app name. All right, so how do we test the manifest JSON and development? So, it's actually pretty easy. With the latest versions of the Chrome browser, for example, uh in the application tab, you have the manifest section where you can just go see that it was loaded properly. And if the developer tools are properly loading your data from the JSON, then you're you're good to go.
09:32 Otherwise, you'll see an error. All right. And of course, when the user after the user launches the app from the home screen and we see the splash screen and it's done saying that the website is already loaded, this is what it's going to look like. We get that full screen experience. Now, before we talk about service workers, we're going to need to understand what a web worker is. And these are relatively new, and it shouldn't sound scary because it's a regular JavaScript file. So, if any of you have ever done any UI on the browser or anything with JavaScript, I'm sure that you've noticed that when you do computationally heavy things, the browser UI freezes. And that's because JavaScript is single threaded. So, a web worker is simply a thread that runs in the background. So, if you're doing kind of intensive stuff, this is the place you're going to want to do it so that you don't hinder the user's experience. Now, a service worker is simply a type of web worker. Now, the main difference that we're going to talk about today or not difference, but uh addition that we're going to talk about today is that service workers are event-driven. So, once we've registered a progressive web app, we can start listening for events that are dispatched from the browsers and act accordingly. All right. And the last thing that you need to know before we get started, like we said earlier, it's only https. It has a predictable life cycle. So we're using that event-driven facet to listen for different things that are being dispatched from the browser. So if you if you've ever done React or Android, there's just a normal lifecycle hook where you can hook your functionality into. It can serve as a programmable network proxy and gives us access to the cache API. All right, so let's talk about what this life cycle is. So, the life cycle is really short. You have the register phase, installation phase, and activation phase. Now we'll talk about what each one does specifically. So, when you're loading your JavaScript in the browser, the first thing you're going to do is want to check that service workers are supported. Now I'll take this opportunity to touch a little bit about support in browsers. So, the support today is pretty widespread.
10:33 Uh it's supported really well in Chrome, Firefox and Opera, and more recently in Safari as well. So this is ongoing, depending on the features you're going to want to use in your app, you should check to see what the backwards compatibility is for browsers, even though today it's pretty good. All right, so once we see the service workers are supported in the browser, we register our service worker, that's when our service worker file is going to be just downloaded to the browser. Uh once that promise resolves, we can move on to the installation phase.
12:04 Now the installation phase is where you're going to want to do the initial setup for your progressive web app, okay? The installation phase is the first event to be fired. It runs once for a given service worker, and we're going to want to take care of things here like caching, which we're going to see in just a second. Things that the app is going to need later within its life cycle. After the installation phase is the activation phase. Now we we're promised by the API that once activation phase is done running, we can start listening for the rest of events that our service workers are going to get. Be that fetch events, push events, background sync events, and many more. So, let's do an example where we see what a pretty simple service worker looks like. This won't be anything complicated. We'll just listen for the life cycle events and make sure that we're logging them properly. So, you have here the regular entry point your app. Mark up, mark up, mark up, and at some point, we're linking to a client JavaScript file. In the uh JavaScript file, like in the previous slide, we're going to check to see that service workers are supported.
13:05 If they are, we can register our service worker. Now, let's take a look at the service worker file. At this point, we're not doing anything special. We're just logging the events that are happening. So, for those of you who didn't know what service workers were up until this point, and it may have sounded maybe complicated or a little bit scary, it's really not and nearly identical to any interaction you may have had with JavaScript up until this point. All right. So, once the service worker is registered, we can see in the browser that all the events are being fired and we also see the order. So, first of all, the first thing that's being logged there on the top is that the browser supports uh service workers, the registration, insulation, and activation. And that's the life cycle. Now, on this last slide here, we're listening for a fetch event. So, let's discuss more what listening to a fetch event actually means and what we can do with it. All right. So, because we're going to be talking about this quite extensively with the cache API, let's understand how it works. So, we're listening for a fetch event, and when the fetch event is invoked or or our browser receives it, uh a callback function is invoked with an event object.
14:11 And what's important for these examples are the request object uh on event. Now, request has a URL, which is the URL that our client is trying to fetch. It has a method, be it put, be it get, be it post, be it delete. And lastly, we have respond with. Now, this is really cool because it lets us specify for a given URL what we want to respond with, what type of resource. So, let's look at a simple example here, and this is a really good way to kind of troll people at work until they figure out that they're service worker working. We'll listen for every event that comes out of the client, and for every event, we'll just return a simple tag with hello. So, for any CSS, any HTML, any JavaScript, any XHR requests, they're just going to get this. All right. Now, this is cool, and it could be funny, but it's not very useful yet. So, let's try to build on this and see where we can take it. All right. So, taking it further, we're going to talk about the cache API. The cache API was designed specifically for service workers, to be able to control programmatically uh responses for given requests.
15:18 Now, under the hood, the cache API is simply a JavaScript map, where every key is a request and every value is a response. So, for if we're looking for flowers.jpeg and we want to maybe cache that uh response to that request, we can decide exactly what the the the client is going to get back. Okay, so let's see how we use it. Something that's important to to know is that on the event object, we have a method called wait until. Now, what wait until does is that it lets us tell the browser, hey, what's happening inside this wait until uh context is critical. Please don't kill the service worker in the middle. So now we're promised that everything that's happening within that bracket will actually get executed from the beginning till the end. Now, in this example, we're simply opening up a cache. Now, cache name here is a string. If it doesn't exist, the browser will create it on the fly. And if it does exist, we're just going to get it back in the promise and and be able to access uh the different values it has set upon it.
16:18 Now, in this example, for every image Beatles.png file that's requested, will return an Arctic Monkeys photo. Again, probably not something you want to do in production, but we're starting to feel what the power could be here. At this point, we just added to the cache though. We haven't done anything with it. We're just saying that in this cache, for every Beatles.png file, we have an Arctic Monkeys response. All right. So now that we know a little bit about how the cache API works, we can talk about different caching strategies. So let's try to build it up from stuff that's more straightforward to things that we might see in production. So the first is cache only. And we came here today for to talk about offline first, not offline only. So it's not probably something you want to do. But for every fetch event, we're going to look into the cache, see if the request already exists. If it does, we'll return it. And if it doesn't, we won't return anything. So this will probably be not a great experience for the users.
17:19 Now, the other end of the spectrum is network only. So if you're not using service workers or doing any caching whatsoever, this is exactly what you have today. For every request, we're just going to let it go out to the network and see if we can get it. All right. So none of these make us feel particularly great. Maybe we can come up with some type of hybrid approach and decide when we want to look into the cache versus when we want to go out and do a network request. All right, so the first example we're going to look at is cache with a network backup. So for every fetch request, XHR, HTML, CSS, or JavaScript, which is leaving the browser, we're first going to check to see if that resource already exists in our cache. If it does, we'll return it. And if it doesn't, then we'll go out to the network. This way, we're making sure that we're not doing any unnecessary network requests. If we have something in the cache, let's serve it up to the user uh and give them a faster, better experience. Now the the next strategy that we're going to look at is network with a cache backup.
18:19 So if you're running something where you have a bias for fresh data, this is probably something that you're going to want to do. Let's first go out to the network, see if we can fetch that resource. If we can't fetch a resource, let's fall back to the cache and try to provide and see if if that uh request has already been recorded there. All right. Now let's take all this and summarize it into an example which many of you may have faced. If you have any type of website that serves images, one of the more terrible things that can happen to your users is no images. So you get the little image, HTML5 image icon with a line through it, and it sucks. So let's try to make sure that after the first load, the user is always going to see an image. So we're going to listen again for a fetch event. In the fetch event, we're going to look for requests that are specifying an image request. Now, if an image is requested, we'll respond with the result of the fetch image uh or fall back method. Now, what fetch image or fall back does is that it takes the request and sends it out to the network.
19:20 If the request fails for any reason, if the response isn't okay, or if an error is thrown during the request, we'll provide a fall back image that was already loaded in our cache. So this is a pretty useful example with probably like 10 lines of JavaScript that could really make a big difference in a user's experience. Lastly, we're going to touch on the web push API. Now, I'm sure many of you have already become familiar with these notifications that are appearing on the top right of your browser or just on your mobile device coming on. And up until recently, or a couple of years ago basically, we could only get these types of notifications for native apps. Now, with the web push API, we have access to it from the browser. Now, we're going to talk about this in two different stages. The first stage is obtaining the authorization from your user your user. So the browser is going to ask your user, are you going to allow or block notifications from this website? Once we have that authorization obtained, we can talk about how we wrap up that notification and and get it delivered to the user's browser.
20:27 So, how do push notifications work behind the scenes, right? Like sudden, like up until a couple years ago, we couldn't do this at all, and now we magically can. So let's spend a couple minutes kind of demystifying what makes it possible. So all major browsers today are maintaining a push service, okay? So Chrome, Safari, Opera, uh and Firefox each have their own push service. Now, the way the push service works is something like this. We have a push subscription at the at the bottom left, and that's what we obtain once we get the users authorization for push notifications. Now, we take that authorization, send it out to our server. Uh our server does whatever it does, basically just wrapping the notification, uh signing it with our server's public and private keys, and sends it out to the browser's push service. Now, at that point, uh the push service acts as a queue, and it promises it promises us if we formatted the request properly, it's going to take care of delivering that push notification to an individual user's browser.
21:31 All right, so how do we get the user permission? So it's actually really simple uh with the clean API. We just use a notification object which is available globally on the on the window scope. And we ask for permission. That's going to that's basically a promise that when it resolves uh this callback, this anonymous callback is going to be called, and in this case, we're not doing anything. We're just logging the response. Now, a more realistic scenario is that we're going to want to save uh that authorization from our user because we're going to want to use it uh moving forward whenever we want to send push notifications via our app. So, after we request permission and the promise is resolved successfully, we create an options object. Now, in the options object, we need to specify our application server key and the field of user visible only, which is currently mandatory on Chrome. It just means that the push notification is going to be visible to the user. We're going to add it via the subscribe uh method to the push manager. And once that's done, we have a push subscription, okay?
22:31 Now, at this point, uh you would actually send that push subscription to the server where that's already the point where you do whatever you want. Usually, you would save that push subscription in a database, and it would be called whenever uh you want to send a push note to the user. Now, we're not going to go into server today because we don't really have enough time, but it's important for me to emphasize that what you do on the sir- like this technology is completely agnostic to whatever backend you want to choose. Um, so, it it should be really easy to add it today to your current product flow uh and road map if you think it's something that can help your users. All right, so how do we handle push events? So we sent out that push subscription to the server. The server forwarded it to the push service, the browser's push service, and the browser push service has kept its promise. It's delivered it back to our user's uh browser. Now, the browser already figures out which uh service worker it's relevant for, dispatches that push event, and what we get is the following: we get a push event with a callback. And here we're not doing any specific styling or adding any extra data.
23:35 We can just show it in a line or two of JavaScript. So today we did a really lighting talk on some of the core APIs available in progressive web app technologies. Um, I hope you you're walking away with this understanding how actually easy it is to start implementing this in your own apps. The the APIs today are well maintained, they're well supported across browsers. And at the end of the day, you can give users a much, much better experience than what they're used to getting out of your mobile website. Uh, thank you a lot for coming today. If you like this, like tech content or specifically PWAs, I post more of it like on my blog or on medium, you're free to follow. And of course, reach out if you want to say hi or have any questions. Thank you.
← When S.O.L.I.D met front-end components · Micro Frontends Architecture & in practice →