Intro To Service Workers & Caching

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] this video is sponsored by dev Mountain if you're interested in learning web development iOS or UX design dev Mountain is a 12-week design and development boot camp intended to get you a full-time position in the industry to learn more visit dev mountain comm or click the link in the description below hey guys welcome to a crash course on serviceworkers and caching so service workers are becoming a huge part of modern web development especially in the area of progressive web apps or PW A's which are applications that that work like more like native apps than web apps now you can do a lot of things with service workers you can have offline content loading which is very popular with pwace also push notifications there's there's something called background sync in this particular tutorial we're gonna first just talk about the basics of service workers and establish what they are talk about some of the events in the API and then we're going to jump in and we're going to take a simple website add a service worker to it that will cache all the pages so that if a user was viewing the site and their connection went out so if they had no internet the pages would still load ok so that's gonna be the focus of this crash course and it's going to be very very basic service workers are kind of difficult to wrap your head around so I'm gonna try to explain things the best that I can and I'm not gonna use any third-party libraries I'm not going to use like work box or anything like that which are really cool tools but I want this to be as vanilla as possible alright so what is a service worker exactly it's it's just a JavaScript file it's a single file that gets registered with the browser and stays with the browser even when you have no internet connection so this means if someone is viewing your website or your application and their connection goes out they're still going to be able to get that information and this is a huge requirement of progressive Web Apps because it makes it seem more like a native app now usually when you go to your browser you enter a URL for a site the browser fetches it and the remote server returns that information to you but when you have a service worker registered it it basically adds another step to the process the service worker kind of jumps in the middle and it can intercept the request and then decide what should happen okay so it's just it decides what can happen with that request in terms of showing the remote version or showing an offline version or whatever it is you want to do and doing this can prevent that that really ugly not found it's not not the 404 pages but you know the default browser page when you're when your internet goes out so you can even have like custom offline pages if you want if you're not going to cache the entire site in general so some other facts about service workers they they can't directly access the Dom the document object model instead they communicate with with the pages it controls by responding to messages sent by something called the post message interface and those pages can then manipulate the Dom if needed but it doesn't access it directly a Service Worker is a programmable network proxy that allows you to control how Network requests from your page are handled service workers are terminated when they're not being used and then they're restarted when they're needed again they also make use of es6 promises so you'll be seeing a lot of dot then dot catch and then a really important part of service workers or a really important piece of information to know is that you need HTTPS unless you're on a local environment and you're using localhost ok so if you upload to a remote server make sure that it has HTTPS installed and enabled so most commonly service workers are used for offline browsing and caching assets and API calls but notifications are also a big part of service workers those are the you know the little notifications that some websites have that'll pop up on your desktop or on your mobile device and they're really great for marketing and advertising and so on and I did do a course on push notification and no js' using service workers I think it was about two months ago that I did it if I remember I'll put the link in the description there's also something called background sink which isn't still isn't fully supported in all browsers but this is a new API that lets you defer actions until the user has a stable connection okay so if a user for instance likes a post on a social network this is a case where something needs to be sent to a server which isn't possible without a connection but with this browser sync API it allows that action to be deferred or basically put on hold in the cache until connectivity is restored and then that post will get liked okay so if you've ever used the Instagram mobile app it works in a very similar way when it's offline now service workers have something called a life cycle and this is a this is a very simplified diagram that I created but basically the first step is to just register the worker then you can install it by triggering the install event and then activate it using the activate event after that it can receive message events and functional events such as fetch which we'll be using and then you also have push for push the push notifications and then sync for the background sync API alright and and this stuff will make more sense when we get into it when we start to work with these events now as far as browser support goes service workers are supported in all major browsers not internet explorer but all normal browsers however the background sync API is not supported in edge or Safari yet as far as I know but it shouldn't be long for them to adapt all right so enough with the slides let's go ahead and jump in and let's take a web site let's add a serviceworker to it so we can cache it and we can have offline viewing of the pages alright guys so we're gonna get started now I just have a very simple website that we're going to be working with so we have a just a simple index page and a simple about page and a CSS file with just a little bit of styling in it so let's take a look at it so I'm going to I'm going to be using live server which is an extension for vs code you can install by clicking on the extensions icon and searching for a live server and installing it and then you can simply say open with live server and it'll open on your local host on port 5500 by default so this is the very simple website and the idea for this is that we want these pages to be available even if the users connection drops okay and we're gonna do that by create registering a service worker and also working with the cache so I'm gonna be opening my chrome tools we're gonna we're gonna work in here quite a bit let me just clear this cache out real quick alright so just make sure okay so right now we have nothing no serviceworker registered all we have is the files I showed you we do have a j/s a main.js file which has nothing in it this is where we're going to register the serviceworker file okay so i'm going to create a file in the root directory this is gonna be our serviceworker i'm gonna call it SW underscore and let's call it cached I'll say cached underscore pages dot j s alright so this is the actual serviceworker but we have to register it elsewhere now you could do it near HTML files but you would have to put in every single HTML file since the main J s is actually included in both HTML files that's where I'm going to register it ok so we're gonna go into main in the first thing you want to do is make sure service workers are supported and we can do that with a simple if statement and we're just gonna say if inside quotes service worker in and then navigator ok navigator is basically like the browser object you can also do if navigator dot Service Worker okay because it's attached to that off so let's just do a quick console.log just majestic to make sure I'm using Chrome so obviously it is it is enabled but we'll just go ahead and do this anyway so we'll say service worker supported okay so we'll save that let's go to our browser and we get service worker supported good now we'll go back we can get rid of this log and we're gonna register it now we want to register it when the window loads okay so in JavaScript we and in the browser we have a window object and we're gonna call an an event listener on it without event listener we want to listen for the load event and then this is gonna take a callback you could put a function like this but I'm gonna be using es6 arrow functions so i'm just going to put a set of parenthesis and then an arrow and then some curly braces and then in here we want to take that navigator object and we want to say dot service work or you can see I'm getting some dropdowns and BS code here and we want to register it with dot register so I'm gonna go on a new line and say dot register and then we want the file name now since the the file the read the Service Worker file is outside of the JavaScript folder where we currently are we have to do a dot dot slash and then the name which is SW underscore cached underscore pages dot J s okay once we do that that's going to give us a promise back so we say dot then it'll give us a registration object and I'm just going to go ahead and console dot log here and again I'm using arrow functions but you don't have to and let's just say here Service Worker and it'll say registered like that alright and then if there's something if something goes wrong then that'll be in the dot catch okay that's how promises work so in here let's just it's going to give us an error and I'm just gonna console dot log and I'm going to put in back ticks here instead of single quotes because I want to include that error variable so I'm gonna say service worker let's say error : and then to put a variable in with with a template string we can just go like that and we can simply put in the error variable that it gives us back right here and that's it that will register the worker so if I save this and we go to Chrome you'll see service worker registered okay and if we go to our application tab and go to service workers you're gonna see it here and it says SW off line pages je s that's the name of the file activated and running it's actually waiting to activate so just ignore that if you see that for now we're gonna take care of it and then this update on reload make sure that this is checked because you want to force the update on page reload so let's go back to vs code now and let's head into our service worker and in here let's see we're going to let's call the install event so I'll say call install event and to do that we need to attach an event listener to the actual worker and we can do that by saying self dot add event listener and we want the install event and that'll we get a callback here you can use function if you want but again I'm using arrow functions and this takes in an event parameter so you want to pass in E or you can do event or whatever you want to do but I like to use just two E and then let's do a console dot log here and let's say service worker and it'll say installed and this should have quotes around it sorry okay so we'll save that and let's go back to Chrome and now you can see it says activated and running and if we go to our console if I reload Italy you might see it flash the installed message see that flash if you want to actually see it you can go to the little gear and preserve your console.log and then reload and now you'll see the service worker installed okay so it just gets installed really quickly and it just flashes but you can see it if you preserve your log so that parts done at least the in the install we have to do some stuff in here but at least we have the event let's now call the activate event actually I'll just copy this here and let's say call activate event so this will be activate and then we'll say service worker activated okay remember that life cycle I showed you in the slides we have the register which happens here and then we have the install and then the activate okay so if we could take a look at that and there's certain things you do in certain areas and so or I should say in certain events so if we preserve the log and reload you'll see installed and activated okay let's go ahead and uncheck that and everything should still be okay here good now this is another tab we're going to be paying attention to cache storage when we actually do cache something it's going to be put into here and then we'll have access to this even if the connection drops and there's no internet connectivity and that's that's the beauty of working with service workers in cache and that's why it's important for progressive Web Apps because you want them to work more like native apps and in most native apps even if the connection drops it doesn't just go blank it doesn't do this if I check offline and I reload we at this ok and this this is a this will simulate offline you know for the if the connection had dropped all right so let's go back to our Service Worker file and now we're going to think about caching so we're going to cache all of our pages we're going to need the assets and the actual HTML pages and I'm going to give you kind of two way to do it first I'm going to show you how to cache the individual pages and then I'm going to show you how to actually cache the entire response that we get okay so the entire website or page so let's create a variable up here we're going to call it cache name that variable can actually be whatever you want this can also be whatever you want but a lot of times you'll see like v1 for version one because you might have different different sets of caches and you want to keep track of them so we'll call this v1 then we need to create a variable of assets so we'll say cash assets and this is going to be an array of all of our pages so we have index dot HTML we have about HTML okay we have a CSS file which is in the CSS folder so CSS slash style dot CSS and then we have our JavaScript file so let's say /j s slash main dot j s so those are the assets that we want to cache and there's there's not a lot in this little website so this is a fine method to do this but if we had a ton of pages then we might want to do the second thing I'm going to show you which is basically just taking the entire response and caching it but for now we're just going to do this and then in the install event is where we want to handle caching these assets so I'm going to go under this console log I'm gonna leave the console logs just to kind of map what's going on but under here we want to say 'i want to take that event parameter and we want to call wait until okay which basically is just telling the browser to wait until our promise is is finished until it it it gets rid of the serviceworker so in here we're going to be using the caches storage API so we're gonna say caches dot open which opens a cache I'm just going to put this on a new line so it opens a cache and we want to pass in our cache name that we defined above okay now once we open it it's going to give us a promise so we want to do dot then it'll give us a cash object and then we want to take that and I'm actually gonna put some curly braces here because I want to do a console.log just to to kind of map what's going on we're gonna say from the service worker so oops so why do I keep forgetting these quotes so from the service worker let's say caching files okay because that's what we're gonna do and we're gonna take that cache object and we're gonna call method called add all and inside here we want to place in our assets that we want to cache which is cash assets that's the array sometimes you'll see people just put the array directly in here but I like to define a variable up here and then put it in and then we just want to add another dot then so when everything is all set we can skip waiting so we can just do a function in here I'm going to use an arrow and we can say self dot skip waiting like that okay so that should actually put the files in the cache so I'm gonna save this and let's head over to Chrome and it already reloaded but I'll just go ahead and reload again and now notice that down here under cache storage there's an arrow and if I click that we'll see our version 1 and if I go on that it's going to show us all the files that have been cached which is basically our entire website the HTML the CSS and the JavaScript gives us the content type the size and the time or the time it was cached and it's now there for offline viewing now we haven't set up that part yet if I were to click offline here and reload we're still going to get this this here I mean we can play this this cool little game here I know this is this is hours of fun but you know it does get old after a while so we're probably going to want to show the website so let's go back and where we want to do this is in the fetch event ok but actually before we do the fetch event let's use our activate in the activate is where we want to clean up any old cache so if I change this to like v2 actually I'll show you real quick if I change it to v2 and I save it and we go and we run this we reload and let's look in cache storage and we have v1 and v2 in here all right so what we want to do is cookies we want to get rid of any unwanted caches so that's that's where we do we do this in the activate event so under this console log let's say remove unwanted caches so again we're going to do our e dot wait until and in here we're gonna say caches dot keys so what what we're doing here is we're going to loop through the caches and we're going to have a condition that basically says if the current cache isn't the cache that we're looping through the current iteration then we want to delete it ok so to do that we do a dot then here because this gives us a promise the cache dot keys and in here we're gonna say cache names okay so for each one we'll call this cache names and we're going to actually have to return a we're gonna do promise dot all and inside here we're gonna take the cache names so cache names and we're going to map through them ok map is just a high order function included in vanilla JavaScript and then for each one we'll call it cash and let's put an arrow function here and let's do a conditional so we'll say if let's say if the cash is not equal to the cash name ok so basically if the current cash we're looping through is not equal to whatever we have here in this case v2 I'm actually going to change it to v1 then what do we want to do we want to delete it so I'm going to put a console dot log here and I'm gonna say a service worker let's say service worker and we'll say clearing old cache okay and to do that we simply need to return caches dot delete it has a delete method and we want to pass in whatever the current cache is as long as it's not equal to the cache name which is the current cache we're dealing with okay and you could use filter here as well but it's fine I'm just gonna do it this way so let's go ahead and save that and it reloads automatically with live servers so I shouldn't have to reload and you can see that now v2 is gone now if I and see the v1 here if I go and change this to v2 and save and we go back now v2 is there and v1 is gone and if we want to look at the console log will preserve the log and reload will see installed caching files actually we don't see the message that it's getting rid of the old cache because I didn't switch it but if I go ahead and switch it back to v1 and save now you'll see right here clearing old cache okay so that's that takes care of that now we need to be able to show our cached files if we're offline so that happens in the fetch event so let's say call fetch event and we're gonna say self dot add eventlistener and we want to listen for fetch so whenever the request is made this should fire off and we can intercept it however we want that's remember I showed you the image of the serviceworker in between chrome and the server that's that's what what we can do here so we're gonna pass in a callback with an event parameter and let's just do a console dot log I know there's a lot of console logs but I want you guys to see the process of how everything works so it's a serviceworker and we'll say fetching and then we want to first check if the live site is available if not then we want to load the cache site so we say e dot respond with and in here we're gonna do fetch jump with this on a new line so in here it's a fetch and what we want to fetch is the initial request so we can get that with the event parameter dot request all right now if this if there's no connection then this is going to fail and since this returns a promise if it fails and it's going to be in the dot catch okay now if there is a if there's a dot catch then we want to put a function in here I'm going to use an arrow and I'm gonna say caches dot match okay so basically what I want to load from the cache and I want to put an e dot request and this will be from the cache so the files whatever we're looking for such as index.html about HTML it'll load it from the cache with this this dot match method okay so hopefully this works so let's go ahead and save it and let's go back to Chrome and we'll reload whoops I spelled fetch wrong of course I did things are going to good so fetch and let's reload here okay and let's unpreserved the log so we don't have all this crap here and then we'll go to our application and let's look at service workers and let's look in the cache we still have all of our files here now since we have that fetch event you can see it says fetching right here we should be able to see the site even if we're offline so let's go to service workers and check offline and reload and there it is okay so we're technically offline right now now if this this is what's being served it's not coming from the server so it doesn't matter if our connection drops all right so let's go ahead and put this back online and reload and now we're back online all right so that's that's one way to do it I don't know why this tab is open now like I said if you want to cache the entire response you can do that but you do that in the actual fetch because you need to first fetch the response and then cache it as opposed to you know doing it up here in the install so I'm gonna create a brand new file here in the route so a new Service Worker I'm gonna call it SW underscore cached instead of cached pages let's call it cached site dot J ass because that's essentially what we're doing is caching the whole site and I'm going to see how do I want to do this well I guess we'll copy what we have here and paste that in except we don't need the cached assets we do want to cache name in fact I'm going to call this v2 and then in the install I'm not going to do the caching here so I'm going to get rid of this this this wait until I'm still gonna leave the event here like that but not I'm not gonna do anything in it activate is gonna stay the same because we still want to clear any old cache but we want to do the real work down here in the fetch ok so we're gonna have a respond with just like we did before let's see it's just clear this so we'll say respond with and then we want to fetch our initial request so e dot request okay and then that will return a promise so we'll do dot then and then we'll get our response and then what we need to do here is basically make a copy of the response that we get from the server so let's say make copy RS actually a clone so make a copy clone of response and we can do that by creating a variable gonna call it res clone and I'm gonna just set it to res and there's actually a method called clone okay so we want to set it to that then we want to open a cache just like we did before and the install except we're doing it down here so we want to call dot open and we want to open cache name which we defined above and then that gives us a promise so dot then and we get our cache object just like before I'm going to set that to set of curly braces and here we want to add the response to the cache so we're gonna say cache dot put okay so we use this put method we take the initial response which are the initial request which is e dot request and then we want to put in res clone which is our copy that we made up here okay so res clone and then we just want to return the original response so down here let's say we want to go under right here and just return res like that now if the connection drops then this dot catch is going to run and we should have our response inside of the cache right at this point so what we can do is this will give us an error and I'm just going to do an arrow function and we can say not catch caches or yeah caches dot match and we just want to put the e dot request because right now it should be in the cache as long as the user went to the site once then it should be in the cache and this will have a dot then because this returns a promise and we simply want to return the response and since we're using arrow functions we can just do it like that if you're using regular callbacks and you just want to return res but that should be good let's save this and now if we go back to our browser and look in our cache storage you'll see we have our index.html that we're currently on plus the assets the stylesheet and JavaScript that that go with it now the about isn't here because we haven't visited it yet so if I click on a boat that'll automatically get pushed to cache okay because remember when we make the fetch in this case we just made a request to or a fetch to the about it's gonna make a copy of it and put it into the cache and now whenever you're offline you should still be able to access those pages in those assets alright so now what I want to do is test this out so I'm gonna push to github ok so we're gonna use github pages so let's go to github.com and the simplest way to use github pages is just creating a repository with your username so mine is Brad traversée and then you want to do dot github dot like that and it'll just say test website and it'll create a repository ok so now I'm not gonna like go over the the basics of git or anything like that I'm just going to push this to it so we can test it out so if you're learning about service workers I'm guessing that you know get so let's just get an it and let's let's add all and then we'll make a commit okay so now that we did that let's add the remote repository so I'm just going to copy this here and paste that in there sorry if you guys can hear that banging outside and doing construction what else we want to do our initial push so I'll grab that and let's push okay Jesus freaking bang and so if I reload this now we have our repository here so let's head to that actual domain which is going to be Brad traversée github do and here's our website and let's open up chrome tools and you can see we have our cache site here and if we look in let's see I'm going to just reload this and if we look in our cache storage we have our index which is slash we have our CSS JavaScript if I go to a boat that gets put in the cached now I'm actually going to test this by shutting off my internet connection so I'm on a Mac I'm just going to go up and this is connected through Wi-Fi so I'm going to turn my Wi-Fi off and let's try it out we'll reload and we still see the site go to a boat it's still there okay and just to prove to you if I go to like let's go to YouTube no connection Gmail no connection udemy no connection and our site works all right so this was this was a very basic tutorial and introduction to service workers like I said there's libraries like work box that net make this stuff a little bit easier but my goal was to give you a tutorial on basically on just vanilla service workers and just how to register them call the install and activate events and then fetch something and put it into the cache that that was the goal for this video and I think we did that so hopefully this helps you guys out I will be doing more at and stuff on service workers in the future including building a progressive web app with probably with react I'm also thinking about doing one with view J s but hopefully you guys like this if you did please hit that like button and I will see you next time
Info
Channel: Traversy Media
Views: 163,356
Rating: 4.9662199 out of 5
Keywords: service workers, javascript service workers, caching, webpage caching, cache, service worker offline, offline webpages, pwa, progressive web app
Id: ksXwaWHCW6k
Channel Id: undefined
Length: 35min 26sec (2126 seconds)
Published: Fri Aug 03 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.