Getting started with progressive web applications through Workbox and service workers

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone Nick Raboy here in this tutorial we're gonna see how to get started with service workers using work box and then how they are relevant when it comes to progressive web application design so PWA so a few things that we're going to explore in this topic and why why should we should even be using service workers or what is a progressive web application so first of all I guess I'll take it back a step a progressive web application is an offline first application it's built typically using modern web technologies so JavaScript CSS HTML it can interact with native host API so whether that be desktop api's or mobile api's things like that just just a whole kind of experience built with the web we're going to be focusing on the caching aspect of things so this is going to be the offline first approach and we're gonna be using work box because when it comes to native service workers doing them by hand there's a lot to take into consideration you have to worry about clearing your cache updating your service work or making sure that things can actually update correctly work box just makes that a whole lot easier so it's a separate framework that makes your life just a little bit easier and that's why we're going to use it so we're gonna see this by example I'm gonna show you some tips and tricks and it will let you rank better when it comes to various google audits it'll give you a user's a better experience so before we even get into the work box side of things let's go ahead and create a new project I'm going to create it on my desktop and this is just gonna be a very simple web application so what I'm gonna do is I'm going to say make directory I'm going to say PW a I'm gonna call it example project I'm going to navigate into it and I'm gonna create a few files so again this is gonna be a very basic web application so what you would expect on a web application is you'll probably have some kind of HTML file so this is going to be an index.html file we also might have some Styles so some CSS and we might also have some scripts so JavaScript now the touch command all at all that's doing is it's creating a new file for me if go ahead and make those files however you feel comfortable doesn't really matter and we're gonna be expanding upon this as we go and you'll notice that I'm using a lot of very basic techniques the idea is not to create a very complex project it's going to show you how to use service workers and how to use work box so let's go ahead and open up this project I'm gonna use Visual Studio code you can use whatever you feel most comfortable with you'll see that I do have the project files open here on the on the Left I'm just gonna open those in new tabs I'm gonna hide the explorer window on the left so that way we get a little more screen real estate I'm also going to open up a terminal so that way you can see the terminal directly within Visual Studio code although we're not going to be using too much of it for this particular tutorial all right so the first step let's go ahead and populate some of these files these are the files that we're gonna be exploring for caching and things like that it's going to start with the scripts file because this is going to be the probably the most basic we're gonna say console.log and we're gonna say hello world pretty basic JavaScript file the goal here is not to show what's inside this javascript file it's the fact that there is a JavaScript file so that way we can cache it later on we're also going to add some styles so we're gonna say body we're just gonna say margin maybe a zero so that way there's no margin on the body we're gonna use a very basic h1 tag let's go ahead and say that there's margin zero on this as well nothing too complicated again just like the scripts file they're going to navigate into the index.html file this is where we're gonna bring everything together and then we're gonna start just looking at the chrome inspector tools and things like that so I'm going to say doctype I'm gonna say HTML I'm gonna say in the head this is where we include the CSS file so we're gonna say link it's gonna be relationship it's gonna be stylesheet we're gonna say href equals style CSS because that's what we've called it outside of the head we have a body and we're going to include that script so we're going to say script I'm gonna say source equals and we're gonna say scripts dot js4 JavaScript now just to show that we actually have stuff on the screen we're gonna say div and we're gonna say maybe h1 and we're gonna say hello world again and we gonna save it now if I go ahead and open this I'm gonna open this in my web browser I'm gonna say open I'm gonna say index.html it's gonna open it's gonna say hello world up at the top it's using the file system URI we're we're gonna change that because when it comes to serviceworkers we can't really use the file system uri we have to be serving it and when it comes to that we have either the option of hosting it or we could run some kind of local development server so we can be using Python candy whatever other locally running kind of deployment tools that you have and grok there's there's so many the list so what we're gonna do I am using a Mac if you're using Mac Linux even even Windows as long as the Python installed you can run a local server so let's go ahead and clear that let's go ahead and say Python - M simple HTTP server and I'm gonna have it serve on port 8000 one serving on port 8000 one I'll go back into my web browser I'm going to say localhost port 8000 1 and as you can see it is still saying hello world so far so good now let's go ahead and look at our chrome inspector so you can say command option J or you can go into I think maybe how you get there manually somewhere around here maybe view developer and then JavaScript console one of these the assumption here is that you're using Google Chrome it's gonna be a little different for every other browser the experience will be different I recommend that you follow along with chrome if you can so you'll notice that I opened up the browser here the inspector it's it's printing out hello world because the JavaScript we can look at Network this is what's gonna be important I'm gonna refresh and you can see that it loaded based on a network request local host styles CSS and JavaScript each one of them they're very small because we don't have a whole lot inside of our files but there is a file size associated to them and there is a time that it took to make that request now if you're hosting it maybe your your hosting servers slow maybe the the network connections poor these times could be significantly larger especially if your file size is larger and let's go ahead and add the index dot HTML extension because it's going to be important when it comes to our examples so that way instead of retrieving localhost we're actually getting that HTML file if we wanted to we could also go to the audit tab so audits and we can run an audit it'll be quick because we don't have much going on here but this is when it comes to pwf so you can see that it doesn't recognize us as a qualified progressive web application I can click it a lot of these won't apply towards this particular tutorials out of the scope but this one right here the page doesn't respond with 201 an offline because we don't have any caching strategy in place through a serviceworker now this other stuff such as the manifest that includes like icons theming colors like that where I can worry about this for this tutorial if you want a 100% support at PWA you'll follow everything unless list but for our sake we're gonna worry about the caching aspect of things so we don't want to have to make these requests every time so let's get into work box so this is the core material of this particular video so let's go back into our code editor what we want to do is actually I can just open up my terminal here I'm going to touch another file I'm gonna create another file I'm gonna call it SW which stands for serviceworker I'm gonna say serviceworker das I can bring back my Explorer open up the serviceworker file let's go ahead and close the Explorer and we can start designing that serviceworker based on work box like I said I've tried doing vanilla serviceworkers with the very basic API s that the web browsers offer it's the api's aren't difficult it's actually the whole strategy behind it and making sure that you're doing it effectively is the difficult part so let's go back into our web browser I'm gonna go to this work box page there's actually instructions if you click on the guides to get start what's interesting to us is this URL right here because we want to add the import scripts so if we copy that line and we paste it in the serviceworker JS file so s wjs then we can actually make use of work box so let's go ahead and make it let's go ahead and try it so we're gonna say let's start with the following let's say work box dot routing dot register route and this is all part of the documentation as well if we if we went back we can actually look through this documentation in fact it's even on the first page as well it's it's very descriptive documentation but there is some parts to be desired so let's just walk through it so we have register route this register route takes a regular expression to determine what would trigger this particular route so let's go to the following let's go ahead and say that this is going to be triggered based on CSS extensions or JavaScript extensions and I am definitely not a regular expression expert so I know that you can get a lot more complex than this but this is a very basic check to say what is the file extension and if it's matching CSS or JavaScript then this is this is the route for us so if if it hits on that we're gonna say new work box dot strategies dot stale while revalidate so there are numerous strategies that you can use there's the two the two that I use the most personally is still while revalidate and then cash first there are a whole lot of others there's some Network first there's there's other things as well the stale rel while you validate revalidate says that you know what when we first request this resource we're always going to request it we're always going to request the CSS and JavaScript files after we request it we're gonna add it to cache and we're gonna do that every time we're always going to read the most recent resource but if a network connection doesn't exist then we are to use the cash so if the network connection doesn't doesn't exist we can't get the latest resource so we're gonna fall back to the cash that's what this is saying but we're always going to update that cash on every request as long as it's possible so stay a while revalidate what we're gonna say is we're gonna name this cash store and we're gonna say cash name let's just call it assets you could say something like CSS JavaScript you can name it whatever makes the most sense to you this is how it's stored in the web browser we're gonna say plugins and we're gonna define maybe an expiration plugin so we're gonna say new work box dot expiration dot plugin there's there's other plugins that you can choose from expiration is one that I use frequently we're gonna say new work box dot expiration actually I just wrote that not paying attention here we're gonna say max entries we're gonna say maybe there's a thousand max entries and then we're gonna give it a long time in seconds before it expires you could do some kind of math let's just go ahead and say max age seconds I believe this is like one year so three three one five six three six and then maybe three or four zeros just know that this is some long time in seconds you can expire after maybe seven days an hour whatever whatever you want if we really want to do we could say expired in 30 minutes I think 1,800 seconds is 30 minutes do some math definitely don't try to freestyle it like I'm doing but this this is what we're saying is we're saying that it's going to expire no matter what so if the internet connection doesn't exist just go ahead and expire it because maybe we don't want to keep cache storage lingering around maybe maybe we want to free up space after a certain amount of time we're gonna we're gonna set an expiration and we don't have to we certainly don't have to provide a cache name we don't have to provide the plugins still while we revalidate will be enough for us that's perfectly fine so let's go ahead and add another route listen let's let's check it out again let's go ahead and copy this so that way it saves us a little bit of typing we're going to make some changes here so we're gonna register the route this time around maybe and I know that we don't have it in our in our project but a good example of this may be images so PNG jpg gif things like that and there's plenty of other image formats as well but maybe we want to use the cache first strategy so in the cache first strategy and first of all let's change that cache name let's go ahead and said maybe images give it a different name the reason by behind the cache first is you know what your images they probably aren't going to change very frequently the need to have to revalidate those images on every request probably a waste of time I'd be surprised if your images change more frequently than 30 days at a time and in fact on my own personal sites I usually set them to a year in terms of expiration it's totally up to you but this is an example of where cache first might make sense so I'm gonna save it now we do have a very appropriate work box serviceworker the thing is it's not wired up yet so it's not being used in our project it exists it's just not being used so we need to register it so we can go back into index dot HTML let's go ahead and add another script and we could have easily done this in the scripts dot JS file but we're gonna we're gonna keep it separated so we're gonna say is we're gonna say script and we're gonna add some simple JavaScript so the first step is we need to check to see if service workers are allowed in this particular web browser even though that support is pretty available for service workers some web browsers may not support them yet or maybe it's not enabled well let's go and say Service Worker in navigator and this this code is actually you can pull it right off of the the work box site as well it's it's pretty common when it comes to service workers but we're checking to see if it's available if yes we're gonna say window dot add event listener so when the window loads we're going to register that service worker so we're going to say something along the lines of navigator dot service worker dot register we're gonna register s wjs because that's the file that we're using this is a promise so we're gonna say then and we're gonna say maybe service worker reg and upon a successful registration we could we could print out a message saying maybe console dot log worker registered if not maybe we want to catch it so we can say catch maybe we say error and we can say something like console about log we can say there was an error and maybe print out whatever that error was and this should work if i if i refresh the page we're still serving with python as you can see in my window below let's go to refresh that page i'm gonna go back into the website here and refresh first of all let's see if there's any errors here so says worker registered I could refresh again because now the page is it's kind of following what that Service Worker set out to do you can see that printed stuff out this is this is only a local host you won't get these these debug logs in production let's go back into the network tab here I'm gonna refresh you'll notice that styles and scripts are now loaded via the Service Worker the time it still takes time but they're not requested from the internet they're requested from the cache and if you go into application you can go to the cache storage you can see that we have assets because remember we we had set up assets we don't have any images because of our application but if we did there would be images here as well but you can see that scripts and styles are stored in the cache and if I went to network they are being loaded from the serviceworker index is not we didn't set it up to store HTML files inside of the cache but we could 21 milliseconds 23 milliseconds kind of a long time I think it was quicker just to pull it from the internet but you have to imagine some things if the files are large maybe these are image files maybe maybe they're complex javascript or css it's going to take a lot longer to pull those from the web especially on a mobile device so progressive web application you want the the mobile experience you don't want them to take a long time you want the experience to be fast and fluid and this is where service workers in caching really helps with that effort so let's go ahead and look it up audit maybe we can run another audit I'll clear the old one let's go to run it again see if anything changed we can click on progressive web app current page doesn't respond with when it's offline that's because HTML we didn't add HTML yet so what we'll revisit this so now the next stage so if we go back into our code we have everything caching at runtime based on the serviceworker what if we wanted to cash a lot of things upfront we could do a pre cache strategy so we can use work box and build so we can build a pre cache strategy we can even build this serviceworker file for all of these runtime strategies and we can actually do that with nodejs if you've been following along with the blog over time you'll remember I did something with gulp because I use hugo from my own website the polyglot developer it doesn't really matter what you do work box will work regardless but we're actually going to pre cache with just simple nodejs and we're gonna we're also going to cache that HTML file so let's go ahead and create another file in our project let's go ahead and say touch generator j/s can be call whatever you want it's not actually part of our application it's part of our development process what we're also gonna do is because this is now because we're building and this is a build time kind of process we're now going to initialize our project for nodejs so we're gonna say npm an it - why and we're going to install work box build so we're gonna say npm install work box build - - dev all right so that that's good to go I'm gonna open up my Explorer real quick I'm gonna open up my generator GS file you'll notice that I do have an ood modules directory and also some package JSON files those are all part of the build scripts so I'm gonna hide the Explorer and I'm gonna say constant work box equals require work box build and now we're going to generate a serviceworker file so we're gonna say work box dot generate SW and we're going to define the configuration so the configuration it's a lot more involved but it's there it everything is described on the work box website so again this is a very valuable website to go to this is part of the Google web tools so let's go ahead and start defining this so first up let's define a cache ID so let's just say maybe this is PW a example for like our example project you can name it whatever you want this is kind of a route kind of storage for our cache we can still individually name each of our runtime caches but this is kind of a global kind of parent level application cache we're gonna find the directory of where to look for our files kind of where to start so we're gonna say glob directory and this is going to be the relative local path right here the the directory that we're already in we're gonna define the things that we want to pre cache so these are the files that we want to cash upfront so we're gonna say glob patterns and this is an array and you can you can put in some wildcards in there as well as what we're going to do so we're gonna say look in every directory look at every file as long as it's a CSS or JavaScript file so basically what we're going to do is we're going to pre cache all JavaScript and all CSS we're not gonna add anything else next up we're going to define an output directory so we're gonna define SW desc it's going to be in our current path we're gonna say swgs so we're just going to name it the same as the the serviceworker file that we had previously created and we're gonna define our runtime configuration caching so we're gonna say runtime caching and this is going to look fairly familiar this is probably gonna be the most familiar part versus what we had previously done so let's go ahead and define a rule so we're gonna say URL pattern we're gonna provide our regex so we're gonna say something like this this time around we're gonna say HTML I think people still use HTML HTM oh I don't see it as much that anymore maybe XML because that's a markup language as well you can really add whatever you want it doesn't really matter whatever makes sense to you we're gonna say what kind of handler this is so this is gonna be a stale while revalidate so it should look familiar and then we're gonna find the options that go with it so the plug-in kind of things to the expirations we're gonna say cache name this time around I'm going to call it markup I'm gonna set an expiration the expiration is going to be something small again max-age seconds again this I think that's 30 minutes bust out a calculator do some math figure out what makes sense to you markup still while revalidate remember it's gonna it's going to download the latest copy every time it's just gonna store it in cash up until the expiration time so let's go ahead and save it let's go ahead and try to run it so what I'm gonna do is I'm gonna say and I'll actually use this terminal down here I'll I'll stop my Python I'm gonna say node generator dot j/s see if it runs looks like it failed to in some fashion I spell runtime caching wrong option is not a supported parameter Oh should be plural so let's go and save it so options not option run it again didn't error out this time I'll look at my serviceworker file you can see that it's little different now because this is auto-generated it still has the import scripts it still has a lot of familiar pieces some new it still has our register route it doesn't look like it pre cached any of our JavaScript or CSS so let's let's revisit on why that could be let's go to generator actually instead of the pipe this time around it should be a comma I think so let's go ahead and run it again look at the serviceworker you can see that it it cached a few things so it cached our scripts like it should cached our Styles had also cache generator which we're going to fix in a second neither precache remember it also has a revision so anytime any of those files change the revision is going to change so that way it recache --is so that way it doesn't use the old cache when our pre cache items change it it just updates it so that way it adds it to the to the cache again so let's fix this we probably don't want generator in our final project so what we can do is we could actually add ignores so let's go ahead and add maybe ignore calab ignores this is an array and similar to the glob that we have on the previous line we could say something like what do we have we have generator j s we have Paul I don't want to cash that service worker jazz file just in case and you know we have a node modules directory you probably want to cash that either so we can say node modules and we're gonna say don't cash any sub directories don't cash any files so I'm gonna save it I'm gonna run it again and I'm gonna go to the Service Worker file and you can see that it removed at this time so it only has this the two files that we wanted it also has that strategy for markup and if I wanted to I can go back into running it so I can say python m simple HTTP server port 88 thousand and one go to my web browser here i'm gonna go back to network see what's going on here so we've another application we could actually manually restart this Service Worker we can update it if we wanted to so let's skip waiting there's actually a command that you can use as part of work box build if you want to have it update on refresh which in a lot of circumstances you might want to do that otherwise it'll update when they close the tab and revisit your website let's go back to Network refresh index it looks like it's part of the Service Worker I can go to the application you can see that I have a markup cache now it has HTML in it I still have assets I have the pre cache which is the JavaScript and CSS assets is no longer being used but this pre cache is so so very interesting stuff that you can do here and as you can see if I if I if I went offline this in theory would still work and that's the beauty of having a progressive web application is it functions like a application it's an offline first application there's plenty of circumstances why this would be good but then again even if you weren't looking at it from the progressive web application perspective when it comes to user experience and performance having a cache is great and serviceworkers makes that very possible and like I said I mean you could play around with service workers manually if you want I definitely recommend using workbox it's kind of the recommended approach makes life a lot easier especially when it comes to figuring out when should your service workers update how do you clear out the cache things like that so this this is a this is a video tutorial on how to use work box how to use service workers how you get to that caching level
Info
Channel: LogRocket
Views: 13,737
Rating: 4.9541984 out of 5
Keywords:
Id: dGWoffJcFhg
Channel Id: undefined
Length: 29min 24sec (1764 seconds)
Published: Thu Nov 14 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.