Lazy-Loaded Images - Code This, Not That

Fireship · Beginner ·💻 AI-Assisted Coding ·7y ago

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 Angular 4 Development and Production Environments with Firebase
Angular 4 Development and Production Environments with Firebase
Fireship
2 OAuth with Angular and Firebase Tutorial
OAuth with Angular and Firebase Tutorial
Fireship
3 Anonymous Authentication with Angular and Firebase - Lazy Registration
Anonymous Authentication with Angular and Firebase - Lazy Registration
Fireship
4 Angular Router Guards for Firebase Users
Angular Router Guards for Firebase Users
Fireship
5 Angular Firebase CRUD App with NoSQL Database Tutorial
Angular Firebase CRUD App with NoSQL Database Tutorial
Fireship
6 Upload Files from Angular to Firebase Storage
Upload Files from Angular to Firebase Storage
Fireship
7 How to Deploy an Angular App to Firebase Hosting
How to Deploy an Angular App to Firebase Hosting
Fireship
8 Sharing Data between Components in Angular
Sharing Data between Components in Angular
Fireship
9 Loading Spinners for Asynchronous Firebase Data
Loading Spinners for Asynchronous Firebase Data
Fireship
10 Angular 4 Transactional Email with Google Firebase Cloud Functions
Angular 4 Transactional Email with Google Firebase Cloud Functions
Fireship
11 Firebase Database Rules Tutorial
Firebase Database Rules Tutorial
Fireship
12 Autocomplete Search with Angular4 and Firebase
Autocomplete Search with Angular4 and Firebase
Fireship
13 Reddit Inspired Upvoting System with Angular and Firebase NoSQL
Reddit Inspired Upvoting System with Angular and Firebase NoSQL
Fireship
14 Angular Drag-and-Drop File Uploads to Firebase Storage
Angular Drag-and-Drop File Uploads to Firebase Storage
Fireship
15 Text Translation with Firebase Cloud Functions onWrite and Angular 4
Text Translation with Firebase Cloud Functions onWrite and Angular 4
Fireship
16 Custom Usernames with Firebase Authentication
Custom Usernames with Firebase Authentication
Fireship
17 Twitter-Inspired Follow Unfollow Feature with Firebase and Angular 4
Twitter-Inspired Follow Unfollow Feature with Firebase and Angular 4
Fireship
18 Simple Pagination with Firebase and Angular 4
Simple Pagination with Firebase and Angular 4
Fireship
19 How to Connect Firebase Users to their Data - 3 Methods
How to Connect Firebase Users to their Data - 3 Methods
Fireship
20 Add Toast Message Notifications to your Angular App
Add Toast Message Notifications to your Angular App
Fireship
21 Facebook-Inspired Reactions System with Angular and Firebase
Facebook-Inspired Reactions System with Angular and Firebase
Fireship
22 Learn NgModule in Angular with Examples
Learn NgModule in Angular with Examples
Fireship
23 Lazy Loading Components in Angular 4
Lazy Loading Components in Angular 4
Fireship
24 Stripe Checkout Payments with Angular and Firebase - Part 1
Stripe Checkout Payments with Angular and Firebase - Part 1
Fireship
25 Process Stripe Payments with Firebase Cloud Functions - Part 2
Process Stripe Payments with Firebase Cloud Functions - Part 2
Fireship
26 Selling Digital Content in Angular with Stripe Payments - Part 3
Selling Digital Content in Angular with Stripe Payments - Part 3
Fireship
27 Angular 4 Full Text Search with Algolia - Part 1
Angular 4 Full Text Search with Algolia - Part 1
Fireship
28 Algolia with Firebase Cloud Functions - Part 2
Algolia with Firebase Cloud Functions - Part 2
Fireship
29 Firebase Phone Authentication in Angular 4
Firebase Phone Authentication in Angular 4
Fireship
30 Top 7 RxJS Concepts for Angular Developers
Top 7 RxJS Concepts for Angular Developers
Fireship
31 Learn Angular Animations with 5 Examples
Learn Angular Animations with 5 Examples
Fireship
32 Advanced Firebase Data Filtering (Multi-Property)
Advanced Firebase Data Filtering (Multi-Property)
Fireship
33 Realtime Maps with Mapbox + Firebase + Angular
Realtime Maps with Mapbox + Firebase + Angular
Fireship
34 Angular Reactive Forms with Firebase Database Backend
Angular Reactive Forms with Firebase Database Backend
Fireship
35 Send Push Notifications in Angular with Firebase Cloud Messaging
Send Push Notifications in Angular with Firebase Cloud Messaging
Fireship
36 Top 7 Ways to Debug Angular 4 Apps
Top 7 Ways to Debug Angular 4 Apps
Fireship
37 Infinite Scroll with Angular and Firebase
Infinite Scroll with Angular and Firebase
Fireship
38 Use TypeScript with Firebase Cloud Functions
Use TypeScript with Firebase Cloud Functions
Fireship
39 Realtime Graphs and Charts with Plotly and Firebase
Realtime Graphs and Charts with Plotly and Firebase
Fireship
40 Role-Based User Permissions in Firebase
Role-Based User Permissions in Firebase
Fireship
41 User Presence System in Realtime - Online, Offline, Away
User Presence System in Realtime - Online, Offline, Away
Fireship
42 Location-based Queries with GeoFire and Angular Google Maps
Location-based Queries with GeoFire and Angular Google Maps
Fireship
43 Angular ngrx Redux Quick Start Tutorial
Angular ngrx Redux Quick Start Tutorial
Fireship
44 Angular Ngrx Effects with Firebase Database
Angular Ngrx Effects with Firebase Database
Fireship
45 Progressive Web Apps with Angular
Progressive Web Apps with Angular
Fireship
46 Angular Ngrx with Firebase Google OAuth User Authentication
Angular Ngrx with Firebase Google OAuth User Authentication
Fireship
47 RxJS Quick Start with Practical Examples
RxJS Quick Start with Practical Examples
Fireship
48 Send SMS Text Messages with Twilio and Firebase
Send SMS Text Messages with Twilio and Firebase
Fireship
49 Firebase Database Performance Profiling
Firebase Database Performance Profiling
Fireship
50 Native Desktop Apps with Angular and Electron
Native Desktop Apps with Angular and Electron
Fireship
51 Subscription Payments with Stripe, Angular, and Firebase
Subscription Payments with Stripe, Angular, and Firebase
Fireship
52 Firestore with AngularFire5 Quick Start Tutorial
Firestore with AngularFire5 Quick Start Tutorial
Fireship
53 Angular HTTP Client Quick Start Tutorial
Angular HTTP Client Quick Start Tutorial
Fireship
54 Google Sign-In with Firestore Custom User Data
Google Sign-In with Firestore Custom User Data
Fireship
55 Star Review System from Scratch with Firestore + Angular
Star Review System from Scratch with Firestore + Angular
Fireship
56 Angular Chatbot with Dialogflow (API.ai)
Angular Chatbot with Dialogflow (API.ai)
Fireship
57 Learn @ngrx/entity and Feature Modules
Learn @ngrx/entity and Feature Modules
Fireship
58 Infinite Scroll Pagination with Firestore
Infinite Scroll Pagination with Firestore
Fireship
59 Faster Firestore via Data Aggregation
Faster Firestore via Data Aggregation
Fireship
60 Contentful - CMS for Angular Progressive Web Apps
Contentful - CMS for Angular Progressive Web Apps
Fireship

Learn how to use IntersectionObserver to lazy-load images efficiently in the browser, improving performance and reducing unnecessary calculations. This technique can be applied to various use cases, such as infinite scroll and animations.

Key Takeaways
  1. Create an IntersectionObserver instance for each image to be lazy-loaded
  2. Define a callback function to handle the intersection of the image with the viewport
  3. Loop over the entries in the callback function to check for intersection
  4. Get the target image element and add the source attribute and fade class when intersecting
  5. Disconnect the observer when the image is loaded to prevent unnecessary work
  6. Apply the IntersectionObserver to all images in the DOM
💡 Using IntersectionObserver can significantly improve browser performance by reducing unnecessary calculations and event listeners, making it a better approach than listening to the scroll event for lazy-loading images.

Related Reads

Up next
FREE WooCommerce Product Custom Fields Plugin Using Claude AI
Quick Tips - Web Desiign & Ai Tools
Watch →