Lazy Loading Images
Load images only when they appear.
Lazy Loading Images is a free JavaScript Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, and your progress syncs across the web and the CoddyKit app. The JavaScript Academy course includes 4 lessons in total.
The Lazy Loading Idea
Lazy loading defers downloading images until they are about to scroll into view. This saves bandwidth and speeds up the initial page load, especially for long, image-heavy pages.
Storing the Real URL
The trick: do not put the real image URL in src initially. Store it in a data-src attribute so the browser does not download it yet.
// Markup pattern:
// <img data-src="photo-large.jpg" alt="Scenery">
// The browser will not fetch anything until we set src.Selecting Lazy Images
Collect all images that need lazy loading. A common convention is a shared class or the presence of data-src.
const lazyImages = document.querySelectorAll('img[data-src]');
console.log('found', lazyImages.length, 'lazy images');Creating the Observer
Make an observer whose callback loads the real image once it intersects. Use rootMargin so the image starts loading slightly before it appears.
const observer = new IntersectionObserver((entries, obs) => {
// handle entries here
}, { rootMargin: '100px' });Loading on Intersection
When an image intersects, copy its data-src into src. The browser then downloads and displays it.
const observer = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src; // triggers the download
}
});
}, { rootMargin: '100px' });Unobserve After Loading
Once loaded, an image never needs watching again. Call unobserve to free resources and prevent re-triggering.
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
obs.unobserve(img); // done watching this one
}Starting Observation
Loop over every lazy image and start observing it. The observer handles the rest as the user scrolls.
lazyImages.forEach(img => observer.observe(img));Showing a Placeholder
Give a smooth experience by displaying a tiny blurred placeholder or solid color while the real image loads, then fade it in on the image's load event.
img.addEventListener('load', () => {
img.classList.add('loaded'); // CSS can fade it in
});
img.src = img.dataset.src;The Native loading Attribute
Modern browsers also support native lazy loading via loading="lazy" on img and iframe. Intersection Observer remains useful for custom control, animations, or fallback behavior.
// Native approach (no JS needed):
// <img src="photo.jpg" loading="lazy" alt="...">
// Observer approach gives more control and effects.Cleaning Up data-src
After loading you may remove the data-src attribute to keep the DOM tidy and avoid confusion in later code or queries.
img.src = img.dataset.src;
img.removeAttribute('data-src');
obs.unobserve(img);The Full Pattern
Lazy loading with Intersection Observer is a tidy, efficient pattern: store URLs in data-src, observe each image, swap in the real URL on intersection, then unobserve. The result is a faster page that loads images just in time.
Quick Check
Test your understanding of lazy loading images.
Recap
You built lazy image loading:
- Store the real URL in
data-src. - Observe each image with an Intersection Observer.
- On intersection, copy
data-srctosrcandunobserve. - Use
rootMarginto preload just before view. - Native
loading="lazy"is a simpler alternative.
Next, we implement infinite scrolling.
Learn JavaScript with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 59
- Lessons
- 200
Frequently Asked Questions
Is the “Lazy Loading Images” lesson free?
Yes — any 3 lessons of the JavaScript Academy learning path, including “Lazy Loading Images”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The JavaScript Academy course includes 4 lessons in total.
What will I learn in “Lazy Loading Images”?
Load images only when they appear. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start JavaScript Academy?
No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.
How long does the “Lazy Loading Images” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this JavaScript Academy lesson?
Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Observing Element Visibility
- Lazy Loading Images
- Infinite Scrolling
- Scroll-Triggered Animations