Check out a free preview of the full Advanced Asynchronous JavaScript course

The "Challenge 4: Preloading Images" Lesson is part of the full, Advanced Asynchronous JavaScript course featured in this preview video. Here's what you'd learn in this lesson:

While the application successfully displays a reference to an image, Jafar notices that the browser's broken image icon is displayed instead of a picture. In this challenge, students are asked how to work around future broken image icons by using observables to preload images successfully.

Preview
Close

Transcript from the "Challenge 4: Preloading Images" Lesson

[00:00:00]
>> Jafar Husain: Broken image. [LAUGH] Well, so that's an actual failure case we have to deal with, right? So we have to worry about broken images. And one of the ways in which we can do that is we can attempt to preload the image before we display it. Does that make sense?

[00:00:14]
Anybody out there know how to preload images in the DOM? You guys are front-end guys. Anybody?
>> Student1: Make an image that is sourced to the thing, and-
>> Jafar Husain: Got you.
>> Student1: LoadEvent or an ErrorEvent.
>> Jafar Husain: Somebody out there who just doesn't go NPM install preloader image, I like it.

[00:00:29]
Old-school, very nice. Yes, absolutely, that's the way in which you can preload an image. So we can create, and whenever you wanna create a preloader image, you can go
>> Jafar Husain: And then go img.onload = function and then img.onerror = function. Make sense? So here we have a callback API.

[00:00:59]
How do we turn this into an observable? Like how do I, I'm gonna express this whole idea of preloading an image as an observable, that I have either fired that image or I guess doesn't. In our case, we kinda wanna filter out images that don't exist, does that make sense?

[00:01:15]
We wanna filter them out, so how am I gonna take, I have a source, right? How do I remove it from the stream unless it's successfully preloaded?
>> Jafar Husain: It's a good place to take a quick break. I want you guys to think about that a little bit, how would we take maybe a function like this that does preloading, and express that as an observable that either fires on next or just on completes, cuz the thing isn't an observable, right?

[00:01:43]
The thing isn't an image, so we wanna filter over it.

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