JavaScript in the Background

Background Fetch

Maximiliano Firtman

Maximiliano Firtman

Independent Consultant
JavaScript in the Background

Check out a free preview of the full JavaScript in the Background course

The "Background Fetch" Lesson is part of the full, JavaScript in the Background course featured in this preview video. Here's what you'd learn in this lesson:

Maximiliano discusses the Background Fetch API, which asks the web engine to make fetch download requests that the browser will download in the background. A walkthrough of the background fetch API script is also covered in this segment.


Transcript from the "Background Fetch" Lesson

>> And the last one before web push is background fetch. I know similar names, right? Background sync, periodic background sync, background fetch. Background fetch is actually a way that the PWA or website has to ask the browser, the rendering engine to download files, completely separate, detached from my window.

So if the user closes the PWA, if the user closes the browser, I want the files to still be downloaded. Maybe you're saying, well, that's like downloading a file. The difference here is that when the files are downloaded, they're not saved in the file system. It will wake your service worker up again.

And it will tell you hey, the files you requested are here. Here you have them. And the service worker will do something with the files, parse them, save them. So it's not downloading files to the file system, it's downloading files to the app itself, okay? So also, the browser will show an OS notification about the process.

On android, it generates, what is known as a fixed notification or one of those notifications that you cannot clear, you cannot remove, it's there until the process is done. And a lot of events will be fired in the Service Worker. Compare with the previous one, this is not just one event.

You have when the download finishes, but also if the user has clicked the notification, maybe that means that the user wants to know what's going on with that, so then you can do something. On abort, on failure, and also on progress. So you can know in your app how's the progress in that download operation.

You can update your UI in case your UI is still there, makes sense? So it's similar to the previous API. We need a service worker registration, and then we call fetch to the background fetch manager. And we need to pass a name, an array of URLs to download, and then metadata.

That metadata will go to the notification. It can be an emash, a logo of your app, your icon. The download total is going to be used for the progress bar but you don't need to provide them it's optional, okay? And that's how you check if the API is there.

And then, you handle events in the Service Worker. Like the backgroundfetchsuccess, where you will get all all your files. Again, what you do with the files, parse them, save them in cache storage. Save them in index dv, I don't know. Backgroundfetchclick, backgroundfetchfailure that those are the most important ones.

To be honest, I've never seen a website using this API. So I've seen the samples I've made but I've never seen a real website actually using this API. And remember, the idea here is that the download process, no matter how long it takes, it will happen even if your app is closed, even if your web app is closed.

Even if your PWA is closed. It takes one day, okay, after a day when the download finishes it will wake up your Service Worker, it will tell you, hey here you have the files you requested. So the idea the originally [COUGH] was to also let us upload data.

But for some reason it's not there yet. So the Chrome team already promised when they presented the API there is also going to work with Apple, that makes sense. I mean, if you wanna upload a video that you are taking from the gallery, that takes time. And right now, you need to keep your web app active.

Well, right now it's only for downloads, okay, make sense? So let's see this in action. So going back here, I have the last one on background execution for background fetch. So we also need the same registration. So, we wait for the registration, and as you can see here we don't have permission to ask, we'll just request the download and it will happen.

Not bother the size that you are downloading, it will start. What we're going to do here is we are going to say, we're going to wait for on the service worker registration, backgroundFetch.fetch. Okay, something like this. And if I wanna, I can keep it's not necessary, but I can keep a constant where I can later cancel that.

It can aboard that later in case I want to or something like that. So the fetch needs a name. For example, I'm going to download media files. It's just an internal name in case you're requesting more than one background fetch. It's just that. It's an identifier. Then an array of files that you wanna download.

For example, we have in our project, the video and the audio files. So we can say media/audio.mp3 and media/video.mp4. So I want those files, okay? And that's all. And then we have an object with metadata. We have the title, Frontend Masters Media files. This is for the notification, okay, and icons.

That's the only mandatory thing. By the way, icons is also using the same format as we used before for the media, okay? The one that I have here for the artwork. It's the same format, okay? So I can just reuse the same object with the same icon. And actually, that's all.

So in this case, we have a really fast connection here. We can change that. I know we can throttle the connection in case we wanna see that, because it's going to be really fast. No, I was using the other Chrome. This one. You need to pay attention to that part of the browser.

Let's see if that works or if I have a typo or something. Register a fetch. Did you see something there appearing? That's the UI. Yeah it's happening really fast, also because these files are cached. That's another situation here, I'm downloading files that were already cached. But that's how it works.

Are these files being downloaded somewhere in the file system, no. The files are being received in the Service Worker, and right now I'm not receiving them. So to receive the files, you need another event handler, addEventListener, okay, with one of the events that we saw before. Such as backgroundfetchsuccess.

Lowercase, no underscores, okay? And you are going to receive the files reference that you can use with the file API directly in an event argument. Make sense? Please remember, Chromium only. Do you have any question?
>> There is no alternative to this for other browsers?
>> The only alternative is to download the files with a fetch in the Service Worker and then the UI.

You won't have any UI, or you can send messages from the Service Worker to the client or something like that. So you can still download files in the Service Worker. The problem is that if it takes a day, okay, probably the browser will kill the Service Worker before the file arrives.

So with this API, no, the browser knows that yeah it will kill the Service Worker, okay? But the browser is downloading the files anyway, even if it takes a day.
>> So are the files available on the event?
>> Yeah.
>> Okay.
>> Yeah, if you look here, you have the thing you have an example.

The files let me make this an async function. It's registration.matchAll. MatchAll will give you all the files so now you have an array of the files in the cache. So the files are in the cache and you can get them if you want and do something with them like putting in another cache of storage or opening them and parsing them.

Typically you use that for downloading video. I mean, if the Frontend Master web app has offline support and you're downloading large video files, well, you can download the video using this technique. So in this case, the Service Worker finishes execution or you close the app or wherever, the browser will still download those files.

And make those files ready for the Service Worker when the download finishes. With this, we've covered background sync, periodic background sync, and background fetch. The last API that we have is the one that most people are waiting for is push. So the question is, what possibilities do we have to work with files today in a browser kind of?

So today you have a full file system API that will let you open files and process those files as bytes. So you can, if you mix that with web assembly, you can have actually anything. So you can parse any files and do whatever you want. But in terms of the typical use case for working with files and fetch typically is to save those files in the cache, so then the Service Worker can serve those files later in the future locally.

That's the most common use case. The other use case is to open the file and do something with it. For example, you can download a zip file. And then you can unzip the file in memory in the Service Worker and take individual files in the archive and do something with them, parse them or store them, make sense?

>> Yeah, very, yes. I've never had to do that, that's awesome.
>> But yeah, today you can download a zip file and the Service Worker can unzip it and then store all the assets individually.
>> And then you mentioned saving it in the cache is that in the browser's cache?

>> In the browser so that kind of. So it's in the browser's cache but today with Service Workers, there is a new API known as the cache storage interface. With the cache storage interface, you have control of a cache. So you can decide which files are going into the cache for how much time and the Service Worker can deliver those files in future navigations, in future page navigations locally.

So everything locally. You can check the workshop I did on PWAs, Progressive Web Apps, something. Also, there are in the Frontend Masters library, there are other courses on I think there is a Kyle Simpson one on there it's also covering Service Workers and the cache storage. So you can get exactly what you can do the power that you have to actually manage the files of your app.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now