Current section: Suspense img 29 exercises
lesson

Intro to Suspense img

Loading lesson

Transcript

00:00 The things you suspend don't have to be data. They can be other types of resources as well like these images. So when you render an image in HTML, maybe it took you some data fetching to get the URL for the image,

00:15 but it also is going to take some fetching to get the image itself. Browsers do funny things when it comes to images. For example, if I'm on a slow network connection, and I've cleared out my cache, I've never seen other images before.

00:33 Watch what happens when I click on Interceptor. I click Interceptor, we are getting the ship, it takes a while, and now we're getting the image. But look, I'm showing all the interceptor data, and it takes a while before the new image is shown. Let's do this again. Click on Galaxy Cluster, it's pending, and now it's not pending, but we're looking at the wrong image.

00:51 This could be really confusing for users who are trying to use our application and running on a slow network. They'll be looking at an old image and not know what's going on. I think that this is a good default browser behavior, and once the data has been cached and everything, then it's plenty fast, like even images, those will come from your disk cache.

01:11 That's all fine, but the thing that I think is confusing for users, is that they're looking at an image for an image that doesn't actually exist. It's not the one that they were requesting. For this reason, I want to have us, if we empty cache and hard reload,

01:29 have a better user experience. By the end of this exercise, we're going to look a little bit more like this, where it takes time to load the data. Once the data is loaded, we're showing the fallback image instead. That way, the user is never left wondering like, wait, is that the interceptor or is that the Galaxy Cruiser or whatever?

01:47 We just show that fallback instead, and we can do this thanks to suspense boundaries and suspending on an image. The way that you do this is you just have to turn whatever resource you're trying to load into a promise. As long as you've got a promise, then you can suspend on it.

02:03 Here's a function that turns loading an image into a promise. We create a new image, we set the source, and once that onload event fires or once that callback is called, we can resolve with the source if you want to. But just triggering, hey, this is ready to go,

02:22 and then you can render a regular image tag and know for sure that this image is now in the browser's disk cache, so you don't have to worry about whether rendering that image tag is going to show the image right away. It will because it's in the browser's cache. That's what we're going to be doing for this exercise.

02:40 I think you're going to enjoy it. Let's get started.