Lazy-Loaded Images - Code This, Not That
Skills:
JavaScript Fundamentals80%
Key Takeaways
This video demonstrates how to use the IntersectionObserver API to lazy-load images efficiently in the browser, comparing it to a less efficient method that listens to the scroll event. It covers the basics of IntersectionObserver, its application in lazy-loading images, and how it can improve performance by reducing unnecessary calculations and event listeners.
Full Transcript
[Music] welcome to another episode of Code This Not That where we try to write the best code possible and avoid the bad stuff today we're going to look at intersection Observer and how to determine the visibility of elements in the Dom this is a very useful tool because you can use it for things like infinite scroll lazy loaded images and animations in today's video we'll look at two different ways we can build out this lazy loaded image feature using nothing but vanilla JavaScript if you're new here like And subscribe and grab the source code from fireship IO and I'll be giving away the first ever fireship IO t-shirt all you have to do is leave a comment below and we'll pick a random winner next week intersection Observer is a browser API that we can use to observe the visibility of an element in the viewport it's currently supported by most browsers with the main exception being Safari but there is a polyfill that you can use as needed I actually use it on fireship iO to Lazy load the comment section the comments live in fire store so this prevents unnecessary reads to the database and another thing you might notice on Fire Ship is that page transitions are are super fast this is made possible in part by a library called quicklink which uses intersection Observer to preload all the links that are visible on the page so there's all kinds of cool use cases but let's go ahead and get started by writing some bad code what we have here is just a basic HTML page and we have some high resolution images on it that we want to Lazy load so when the user Scrolls to an image it will load it and then do this little CSS animation the CSS itself is pretty straightforward we start with an opacity of zero in a transform and then we fade in by adding this fade class which sets the OPAC capacity to one then in the HTML we'll go ahead and reference a script called appjs and that'll be a deferred script then you'll notice with the images in this page that instead of having a source attribute they have a data lazy attribute this is our own custom attribute that we can use to point to the image itself and then we'll use our JavaScript to set it as the actual image source when it becomes visible in the viewport the first thing we'll do is grab all of the images in the Dom by using query selector all then we'll listen to The Scroll event on the window and every time the user Scrolls we'll be able to recalculate whether not an element is visible after that we can Loop over each image and run the calculation the calculation is determined by the get bounding client wct value so we'll be looking at the top of the element if the top of the element is less than or equal to the window inner height then we know that it's visible from there we'll go ahead and read the data lazy attribute so we know the true source of the image and once we have that value we'll just go ahead and call set attributes for the source and we'll also go ahead and add that fade class to run the animation so that code's actually very simple and it works but it's also very inefficient and will very likely cause performance issues if we go back to the demo you can see that I'm console pooping every time that calculation runs by the time we get to the bottom of the page we've already taken over 3,000 console poops and not only that but the event listener is still running even after all the images load so it's doing all the calculations for no reason in the background on the main thread let's see how we can use intersection Observer to clean up this mess we'll start with a function called lazy load that takes a Dom element as its argument then we'll create an intersection Observer for each image that we want to Lazy load it has a callback function that has the entries which are the actual observations on the element and then Observer is the interface that we can use to manage the actual instance of this Observer by default it will listen to the top level viewport on the document but you can pass in an options object if you want to listen to a specific div or element at this point I want to make a note that you can use a single intersection Observer to listen to multiple images but in this demo I'm going to give each image its own Observer and I'll show you why in just a minute the next step is to Loop over the entries and see if any of them are intersecting with the viewport and fortunately we don't have to do any of our own calculation we can just call entry is intersecting which will return a Boolean true or false however there are situations where you probably want to do some calculations here so you have access to all of the bounding boxes for the elements from here we need to get the actual image that has intersected with the window which we can do by calling entry Target and then we can run the same logic that we did in the previous example that adds the attribute and the fade class now at this point we know the image is visible so we can of the Observer by calling Observer disconnect that means we won't have any unnecessary work happening on the main thread like we did in the previous example and it's also why I set up an observer for each image the last thing we need to do in this function is call observe on the target element and then finally we'll Loop over all of the elements in the Dom and apply this Observer to them when we reload the page we get seven console logs initially which are for the seven images on the page then as we scroll down we'll start to intersect with the images and Trigger additional console logs in total our code only runs 13 times which is much better than the 4,000 poops we took a few minutes ago I'm going to go ahead and wrap things up there if this video helped you please like And subscribe thanks for watching and I will talk to you soon [Music]
Original Description
Code this 💪, not that 💩. Learn how to use IntersectionObserver to lazy-load images efficiently in the browser without listening to the scroll event https://fireship.io/snippets/intersection-observer-lazy-load-images/
API https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Fireship · Fireship · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Angular 4 Development and Production Environments with Firebase
Fireship
OAuth with Angular and Firebase Tutorial
Fireship
Anonymous Authentication with Angular and Firebase - Lazy Registration
Fireship
Angular Router Guards for Firebase Users
Fireship
Angular Firebase CRUD App with NoSQL Database Tutorial
Fireship
Upload Files from Angular to Firebase Storage
Fireship
How to Deploy an Angular App to Firebase Hosting
Fireship
Sharing Data between Components in Angular
Fireship
Loading Spinners for Asynchronous Firebase Data
Fireship
Angular 4 Transactional Email with Google Firebase Cloud Functions
Fireship
Firebase Database Rules Tutorial
Fireship
Autocomplete Search with Angular4 and Firebase
Fireship
Reddit Inspired Upvoting System with Angular and Firebase NoSQL
Fireship
Angular Drag-and-Drop File Uploads to Firebase Storage
Fireship
Text Translation with Firebase Cloud Functions onWrite and Angular 4
Fireship
Custom Usernames with Firebase Authentication
Fireship
Twitter-Inspired Follow Unfollow Feature with Firebase and Angular 4
Fireship
Simple Pagination with Firebase and Angular 4
Fireship
How to Connect Firebase Users to their Data - 3 Methods
Fireship
Add Toast Message Notifications to your Angular App
Fireship
Facebook-Inspired Reactions System with Angular and Firebase
Fireship
Learn NgModule in Angular with Examples
Fireship
Lazy Loading Components in Angular 4
Fireship
Stripe Checkout Payments with Angular and Firebase - Part 1
Fireship
Process Stripe Payments with Firebase Cloud Functions - Part 2
Fireship
Selling Digital Content in Angular with Stripe Payments - Part 3
Fireship
Angular 4 Full Text Search with Algolia - Part 1
Fireship
Algolia with Firebase Cloud Functions - Part 2
Fireship
Firebase Phone Authentication in Angular 4
Fireship
Top 7 RxJS Concepts for Angular Developers
Fireship
Learn Angular Animations with 5 Examples
Fireship
Advanced Firebase Data Filtering (Multi-Property)
Fireship
Realtime Maps with Mapbox + Firebase + Angular
Fireship
Angular Reactive Forms with Firebase Database Backend
Fireship
Send Push Notifications in Angular with Firebase Cloud Messaging
Fireship
Top 7 Ways to Debug Angular 4 Apps
Fireship
Infinite Scroll with Angular and Firebase
Fireship
Use TypeScript with Firebase Cloud Functions
Fireship
Realtime Graphs and Charts with Plotly and Firebase
Fireship
Role-Based User Permissions in Firebase
Fireship
User Presence System in Realtime - Online, Offline, Away
Fireship
Location-based Queries with GeoFire and Angular Google Maps
Fireship
Angular ngrx Redux Quick Start Tutorial
Fireship
Angular Ngrx Effects with Firebase Database
Fireship
Progressive Web Apps with Angular
Fireship
Angular Ngrx with Firebase Google OAuth User Authentication
Fireship
RxJS Quick Start with Practical Examples
Fireship
Send SMS Text Messages with Twilio and Firebase
Fireship
Firebase Database Performance Profiling
Fireship
Native Desktop Apps with Angular and Electron
Fireship
Subscription Payments with Stripe, Angular, and Firebase
Fireship
Firestore with AngularFire5 Quick Start Tutorial
Fireship
Angular HTTP Client Quick Start Tutorial
Fireship
Google Sign-In with Firestore Custom User Data
Fireship
Star Review System from Scratch with Firestore + Angular
Fireship
Angular Chatbot with Dialogflow (API.ai)
Fireship
Learn @ngrx/entity and Feature Modules
Fireship
Infinite Scroll Pagination with Firestore
Fireship
Faster Firestore via Data Aggregation
Fireship
Contentful - CMS for Angular Progressive Web Apps
Fireship
More on: JavaScript Fundamentals
View skill →Related Reads
🎓
Tutor Explanation
DeepCamp AI