JavaScript and TypeScript course ยท Module 9: Design Patterns and Architecture
Lazy loading - images, routes, components
In this lesson8
Imagine a visitor who has to collect the maps of every sector at the park gate before taking a single step, which is exactly what an application that loads everything at startup does. Lazy loading is an optimization strategy that delays loading resources until they are actually needed: when the user scrolls the page, navigates to a new route or performs an action that requires a specific component.
Benefits of lazy loading
You get a faster initial load: a smaller initial bundle, faster rendering of the first content (FCP) and a better perceived performance. You save RAM, data transfer and battery on mobile devices. The user gets smooth scrolling, progressive content loading and an experience adapted to the capabilities of the device and the connection.
Lazy loading images
Native lazy loading in HTML
The simplest approach needs no JavaScript. The loading attribute tells the browser when to fetch an image:
<!-- Native lazy loading for images below the fold (supported by modern browsers) -->
<img src="gallery-photo.jpg" alt="Gallery photo" loading="lazy" />
<!-- Eager loading for above-the-fold images -->
<img src="logo.jpg" alt="Logo" loading="eager" />
<!-- No attribute: eager by default ("auto" is not part of the HTML standard) -->
<img src="banner.jpg" alt="Banner" />The standard knows only the values lazy and the default eager. Do not mark images that are visible right away as lazy, because you will delay the largest element of the page, and by setting width and height you avoid layout shifts.
Intersection Observer API
When you need more control, use Intersection Observer. This API reports when an element enters the visible area (viewport) without listening to every scroll:
// Lazy loading implementation with Intersection Observer
class LazyImageLoader {
constructor() {
this.imageObserver = new IntersectionObserver(
this.handleIntersection.bind(this),
{
root: null, // viewport
rootMargin: '50px', // load 50px before entering viewport
threshold: 0.1 // trigger when 10% of image is visible
}
);
this.initLazyImages();
}
initLazyImages() {
const lazyImages = document.querySelectorAll('img[data-src]');
lazyImages.forEach(img => {
this.imageObserver.observe(img);
});
}
handleIntersection(entries) {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
this.loadImage(img);
this.imageObserver.unobserve(img);
}
});
}
loadImage(img) {
// Load image from the data-src attribute
img.src = img.dataset.src;
img.classList.add('loaded');
// Remove data-src after loading
delete img.dataset.src;
// Error handling for loading
img.onerror = () => {
img.src = '/images/error-placeholder.png';
img.classList.add('error');
};
}
}
// Initialization
document.addEventListener('DOMContentLoaded', () => {
new LazyImageLoader();
});The address waits in data-src until the image enters the viewport, and unobserve makes sure each image loads only once.
React components for lazy loading images
In React we wrap this logic in the useIntersectionObserver hook and the LazyImage component:
// Hook for lazy loading images
import { useState, useRef, useEffect } from 'react';
function useIntersectionObserver(options = {}) {
const [isIntersecting, setIsIntersecting] = useState(false);
const [hasIntersected, setHasIntersected] = useState(false);
const elementRef = useRef(null);
useEffect(() => {
const element = elementRef.current;
if (!element) return;
const observer = new IntersectionObserver(
([entry]) => {
const isElementIntersecting = entry.isIntersecting;
setIsIntersecting(isElementIntersecting);
if (isElementIntersecting && !hasIntersected) {
setHasIntersected(true);
}
},
{ threshold: 0.1, rootMargin: '50px', ...options }
);
observer.observe(element);
return () => observer.disconnect();
}, [hasIntersected, options]);
return { elementRef, isIntersecting, hasIntersected };
}
// LazyImage component
function LazyImage({ src, alt, placeholder, className = '' }) {
const [imageLoaded, setImageLoaded] = useState(false);
const [imageError, setImageError] = useState(false);
const { elementRef, hasIntersected } = useIntersectionObserver();
const handleImageLoad = () => {
setImageLoaded(true);
};
const handleImageError = () => {
setImageError(true);
};
return (
<div ref={elementRef} className={`lazy-image-container ${className}`}>
{/* Placeholder shown during loading */}
{!imageLoaded && (
<img
src={placeholder}
alt={`${alt} placeholder`}
className="placeholder-image"
/>
)}
{/* Actual image loaded lazily */}
{hasIntersected && (
<img
src={imageError ? '/images/error.png' : src}
alt={alt}
onLoad={handleImageLoad}
onError={handleImageError}
className={`lazy-image ${imageLoaded ? 'loaded' : 'loading'}`}
/>
)}
{/* Loading spinner */}
{hasIntersected && !imageLoaded && !imageError && (
<div className="image-spinner">Loading...</div>
)}
</div>
);
}
// Component usage
function Gallery({ images }) {
return (
<div className="gallery">
{images.map((image, index) => (
<LazyImage
key={index}
src={image.url}
alt={image.alt}
placeholder={image.placeholder}
className="gallery-item"
/>
))}
</div>
);
}Note: the default options = {} is a new object on every render, so the effect recreates the observer on every render. In production, pass a stable object.
Progressive Image Loading
A well-known effect: a blurred preview smoothly turns into a sharp image:
// Component with progressive loading (blur -> sharp)
function ProgressiveImage({ src, placeholder, alt }) {
const [imageLoaded, setImageLoaded] = useState(false);
const { elementRef, hasIntersected } = useIntersectionObserver();
return (
<div ref={elementRef} className="progressive-image">
{/* Blurred placeholder */}
<img
src={placeholder}
alt={alt}
className={`progressive-placeholder`}
style={{
filter: 'blur(10px)',
transition: 'opacity 0.3s ease'
}}
/>
{/* Sharp image */}
{hasIntersected && (
<img
src={src}
alt={alt}
onLoad={() => setImageLoaded(true)}
className={`main-image ${imageLoaded ? 'visible' : 'hidden'}`}
style={{
opacity: imageLoaded ? 1 : 0,
transition: 'opacity 0.3s ease'
}}
/>
)}
</div>
);
}The lightweight placeholder is visible right away, and the full image fades in only after the onLoad event.
Lazy loading routes (Route-based)
React Router with Suspense
You gain the most by splitting code by routes. You define the page component, wrap it with the lazy function and a dynamic import(), and add a Suspense boundary with a fallback component:
import { Suspense, lazy } from 'react';
import { Routes, Route } from 'react-router';
import ErrorBoundary from './components/ErrorBoundary';
import LoadingSpinner from './components/LoadingSpinner';
// Lazy loading route components
const HomePage = lazy(() => import('./pages/HomePage'));
const ProductsPage = lazy(() => import('./pages/ProductsPage'));
const ProductDetailPage = lazy(() => import('./pages/ProductDetailPage'));
const UserProfilePage = lazy(() => import('./pages/UserProfilePage'));
const AdminPanel = lazy(() => import('./pages/AdminPanel'));
// Components with custom loading and error handling
const LazyRoute = ({ children }) => (
<ErrorBoundary>
<Suspense fallback={<LoadingSpinner />}>
{children}
</Suspense>
</ErrorBoundary>
);
function App() {
return (
<Routes>
<Route path="/" element={<LazyRoute><HomePage /></LazyRoute>} />
<Route path="/products" element={<LazyRoute><ProductsPage /></LazyRoute>} />
<Route path="/products/:id" element={<LazyRoute><ProductDetailPage /></LazyRoute>} />
<Route path="/profile" element={<LazyRoute><UserProfilePage /></LazyRoute>} />
<Route path="/admin/*" element={<LazyRoute><AdminPanel /></LazyRoute>} />
</Routes>
);
}A dynamic import() returns a Promise that resolves to the module, and the bundler moves each page into a separate file. Without React it is simply const module = await import('./module.js'). lazy requires a default export, and ErrorBoundary catches a failed download.
Advanced route loading strategies
A route can be fetched before the user clicks: on hovering over a link, based on the predicted path, or while the browser is idle:
// Preloading routes based on user behavior
class RoutePreloader {
constructor() {
this.preloadedRoutes = new Set();
this.setupPreloading();
}
setupPreloading() {
// Preload on hover
this.setupHoverPreloading();
// Preload based on probability
this.setupPredictivePreloading();
// Preload in idle time
this.setupIdlePreloading();
}
setupHoverPreloading() {
document.addEventListener('mouseover', (e) => {
const link = e.target.closest('a[href]');
if (link && this.shouldPreload(link.href)) {
this.preloadRoute(new URL(link.href).pathname);
}
});
}
setupPredictivePreloading() {
// If user is on /products, preload /products/:id
const currentPath = window.location.pathname;
if (currentPath === '/products') {
// Delay so as not to affect current page load
setTimeout(() => {
this.preloadRoute('/products/:id');
}, 2000);
}
}
setupIdlePreloading() {
if ('requestIdleCallback' in window) {
requestIdleCallback(() => {
this.preloadCriticalRoutes();
});
}
}
preloadRoute(path) {
if (this.preloadedRoutes.has(path)) return;
const routeMap = {
'/products': () => import('./pages/ProductsPage'),
'/products/:id': () => import('./pages/ProductDetailPage'),
'/profile': () => import('./pages/UserProfilePage'),
'/admin': () => import('./pages/AdminPanel')
};
const preloadFunction = routeMap[path];
if (preloadFunction) {
preloadFunction().then(() => {
this.preloadedRoutes.add(path);
console.log(`Route ${path} preloaded`);
});
}
}
shouldPreload(href) {
// Preload only internal links
return href.startsWith(window.location.origin);
}
preloadCriticalRoutes() {
const critical = ['/products', '/profile'];
critical.forEach(route => this.preloadRoute(route));
}
}
// Initialization
new RoutePreloader();requestIdleCallback waits until the browser has nothing more urgent to do (the code checks whether the function exists).
Lazy loading components
Component-level lazy loading
Heavy components, such as charts or a code editor, are loaded only after the tab that needs them is opened:
// Lazy loading expensive components
const ExpensiveChart = lazy(() => import('./components/ExpensiveChart'));
const DataVisualization = lazy(() => import('./components/DataVisualization'));
const VideoPlayer = lazy(() => import('./components/VideoPlayer'));
const CodeEditor = lazy(() => import('./components/CodeEditor'));
function Dashboard({ activeTab, data }) {
return (
<div className="dashboard">
<nav className="dashboard-nav">
{/* Navigation always visible */}
</nav>
<main className="dashboard-content">
{activeTab === 'charts' && (
<Suspense fallback={<div>Loading charts...</div>}>
<ExpensiveChart data={data} />
</Suspense>
)}
{activeTab === 'visualization' && (
<Suspense fallback={<div>Loading visualization...</div>}>
<DataVisualization data={data} />
</Suspense>
)}
{activeTab === 'video' && (
<Suspense fallback={<div>Loading player...</div>}>
<VideoPlayer />
</Suspense>
)}
{activeTab === 'editor' && (
<Suspense fallback={<div>Loading editor...</div>}>
<CodeEditor />
</Suspense>
)}
</main>
</div>
);
}The navigation appears immediately, and each tab has its own fallback.
Modal and drawer lazy loading
Only some users ever open the modals, so the useLazyModal hook imports them only after a click:
// Hook for lazy modals
function useLazyModal() {
const [isOpen, setIsOpen] = useState(false);
const [Component, setComponent] = useState(null);
const openModal = async (modalType) => {
const modalMap = {
'user-settings': () => import('./modals/UserSettingsModal'),
'payment': () => import('./modals/PaymentModal'),
'image-editor': () => import('./modals/ImageEditorModal'),
};
const importFunction = modalMap[modalType];
if (importFunction) {
const { default: ModalComponent } = await importFunction();
setComponent(() => ModalComponent);
setIsOpen(true);
}
};
const closeModal = () => {
setIsOpen(false);
// Optionally: unload component after closing
setTimeout(() => setComponent(null), 300);
};
return { Component, isOpen, openModal, closeModal };
}
// Using lazy modals
function App() {
const { Component: ModalComponent, isOpen, openModal, closeModal } = useLazyModal();
return (
<div>
<button onClick={() => openModal('user-settings')}>
User Settings
</button>
<button onClick={() => openModal('payment')}>
Payment
</button>
<button onClick={() => openModal('image-editor')}>
Image Editor
</button>
{isOpen && ModalComponent && (
<Suspense fallback={<div>Loading...</div>}>
<ModalComponent onClose={closeModal} />
</Suspense>
)}
</div>
);
}Writing setComponent(() => ModalComponent) is necessary, because useState would treat a function passed directly as a state updater.
Feature-based lazy loading
Whole features, such as the admin panel or the cart, are loaded with a skeleton instead of a spinner:
// Lazy loading entire features
const AdminFeature = lazy(() => import('./features/Admin'));
const AnalyticsFeature = lazy(() => import('./features/Analytics'));
const ShoppingCartFeature = lazy(() => import('./features/ShoppingCart'));
function FeatureLoader({ feature, ...props }) {
const featureMap = {
admin: AdminFeature,
analytics: AnalyticsFeature,
cart: ShoppingCartFeature
};
const FeatureComponent = featureMap[feature];
if (!FeatureComponent) {
return <div>Unknown feature: {feature}</div>;
}
return (
<ErrorBoundary>
<Suspense fallback={<FeatureLoadingSkeleton feature={feature} />}>
<FeatureComponent {...props} />
</Suspense>
</ErrorBoundary>
);
}
// Skeleton for different features
function FeatureLoadingSkeleton({ feature }) {
const skeletons = {
admin: <AdminSkeleton />,
analytics: <ChartsSkeleton />,
cart: <CartSkeleton />
};
return skeletons[feature] || <DefaultSkeleton />;
}A skeleton shows the shape of the upcoming content, so the page jumps around less.
Advanced lazy loading techniques
Virtual scrolling with lazy loading
Virtual scrolling renders only the visible rows of a long list, here with the react-window library:
// Virtual scrolling for large lists
import { List } from 'react-window';
function VirtualizedList({ items, itemHeight = 50 }) {
const [loadedItems, setLoadedItems] = useState(new Set());
const loadItem = useCallback(async (index) => {
if (loadedItems.has(index)) return;
// Simulate data loading
await new Promise(resolve => setTimeout(resolve, 100));
setLoadedItems(prev => new Set([...prev, index]));
}, [loadedItems]);
const Row = ({ index, style }) => {
const item = items[index];
const isLoaded = loadedItems.has(index);
useEffect(() => {
if (!isLoaded) {
loadItem(index);
}
}, [index, isLoaded, loadItem]);
return (
<div style={style} className="list-item">
{isLoaded ? (
<ItemContent item={item} />
) : (
<ItemSkeleton />
)}
</div>
);
};
return (
<List
style={{ height: 400 }}
rowComponent={Row}
rowCount={items.length}
rowHeight={itemHeight}
rowProps={{}}
overscanCount={5} // Preload 5 items beyond viewport
/>
);
}overscanCount renders a few extra rows outside the viewport, so fast scrolling does not reveal empty space.
Lazy loading with cache
ComponentCache keeps components in a map, and preload fetches them in advance:
// Cache for lazy-loaded components
class ComponentCache {
constructor() {
this.cache = new Map();
}
async get(key, loader) {
if (this.cache.has(key)) {
return this.cache.get(key);
}
const component = await loader();
this.cache.set(key, component);
return component;
}
preload(key, loader) {
if (!this.cache.has(key)) {
this.get(key, loader);
}
}
clear(key) {
if (key) {
this.cache.delete(key);
} else {
this.cache.clear();
}
}
}
const componentCache = new ComponentCache();
// Hook utilizing cache
function useLazyComponent(componentKey, loader) {
const [Component, setComponent] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const loadComponent = useCallback(async () => {
if (Component) return;
setLoading(true);
setError(null);
try {
const loadedComponent = await componentCache.get(componentKey, loader);
setComponent(() => loadedComponent.default);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
}, [componentKey, loader, Component]);
// Preload function
const preload = useCallback(() => {
componentCache.preload(componentKey, loader);
}, [componentKey, loader]);
return { Component, loading, error, loadComponent, preload };
}The browser will not execute a module twice anyway, but your own map gives you control: clearing, statistics or an expiry time (TTL).
Connection-aware lazy loading
On a slow connection we load less, and in lower quality. The Network Information API reports the effective connection type (effectiveType):
// Adaptive loading based on connection
function useConnectionAwareLazyLoading() {
const [connectionType, setConnectionType] = useState('4g');
useEffect(() => {
const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (connection) {
setConnectionType(connection.effectiveType);
const updateConnection = () => {
setConnectionType(connection.effectiveType);
};
connection.addEventListener('change', updateConnection);
return () => connection.removeEventListener('change', updateConnection);
}
}, []);
const shouldLazyLoad = useCallback((priority = 'normal') => {
const strategies = {
'4g': { immediate: true, normal: true, low: true },
'3g': { immediate: true, normal: true, low: false },
'2g': { immediate: true, normal: false, low: false },
'slow-2g': { immediate: false, normal: false, low: false }
};
return strategies[connectionType]?.[priority] ?? false;
}, [connectionType]);
const getLoadingStrategy = useCallback(() => {
const strategies = {
'4g': 'aggressive', // Load everything
'3g': 'moderate', // Load only when needed
'2g': 'conservative', // Load minimally
'slow-2g': 'minimal' // Only essentials
};
return strategies[connectionType] || 'moderate';
}, [connectionType]);
return { connectionType, shouldLazyLoad, getLoadingStrategy };
}
// Component adapting to connection
function AdaptiveImageGrid({ images }) {
const { shouldLazyLoad, getLoadingStrategy } = useConnectionAwareLazyLoading();
const strategy = getLoadingStrategy();
const imageSettings = {
aggressive: { quality: 'high', eager: 10 },
moderate: { quality: 'medium', eager: 4 },
conservative: { quality: 'low', eager: 2 },
minimal: { quality: 'thumbnail', eager: 1 }
};
const settings = imageSettings[strategy];
return (
<div className="image-grid">
{images.map((image, index) => (
<AdaptiveImage
key={image.id}
src={image.url}
quality={settings.quality}
placeholder={image.placeholder}
loading={index < settings.eager ? 'eager' : 'lazy'}
shouldOptimize={strategy !== 'aggressive'}
/>
))}
</div>
);
}This API works only in Chromium-based browsers, which is why the hook starts with the value '4g' and checks whether navigator.connection exists.
Performance monitoring for lazy loading
You cannot judge an optimization by eye. LazyLoadingMonitor measures loading time, errors and cache hits:
// Lazy loading performance monitoring
class LazyLoadingMonitor {
constructor() {
this.metrics = {
componentsLoaded: 0,
totalLoadTime: 0,
failedLoads: 0,
cacheHits: 0
};
this.startTime = performance.now();
}
trackComponentLoad(componentName, loadTime, fromCache = false) {
this.metrics.componentsLoaded++;
this.metrics.totalLoadTime += loadTime;
if (fromCache) {
this.metrics.cacheHits++;
}
// Web Vitals tracking
if (loadTime > 2500) { // Slow loading threshold
console.warn(`Slow lazy load detected: ${componentName} took ${loadTime}ms`);
}
// Send to analytics
this.sendMetrics('component_lazy_load', {
component: componentName,
loadTime,
fromCache,
timestamp: Date.now()
});
}
trackFailedLoad(componentName, error) {
this.metrics.failedLoads++;
console.error(`Failed to lazy load ${componentName}:`, error);
this.sendMetrics('component_lazy_load_error', {
component: componentName,
error: error.message,
timestamp: Date.now()
});
}
getAverageLoadTime() {
return this.metrics.componentsLoaded > 0
? this.metrics.totalLoadTime / this.metrics.componentsLoaded
: 0;
}
getCacheHitRate() {
return this.metrics.componentsLoaded > 0
? (this.metrics.cacheHits / this.metrics.componentsLoaded) * 100
: 0;
}
sendMetrics(event, data) {
// Integration with Google Analytics, Mixpanel, etc.
if (typeof gtag !== 'undefined') {
gtag('event', event, data);
}
}
generateReport() {
const sessionTime = performance.now() - this.startTime;
return {
sessionDuration: sessionTime,
componentsLoaded: this.metrics.componentsLoaded,
averageLoadTime: this.getAverageLoadTime(),
cacheHitRate: this.getCacheHitRate(),
failureRate: (this.metrics.failedLoads / Math.max(1, this.metrics.componentsLoaded + this.metrics.failedLoads)) * 100,
totalFailures: this.metrics.failedLoads
};
}
}
// Singleton instance
const lazyLoadMonitor = new LazyLoadingMonitor();
// Hook with monitoring
function useMonitoredLazyComponent(componentName, loader) {
const [Component, setComponent] = useState(null);
const [loading, setLoading] = useState(false);
const loadComponent = useCallback(async () => {
if (Component) return;
const startTime = performance.now();
setLoading(true);
try {
const loadedComponent = await loader();
const loadTime = performance.now() - startTime;
setComponent(() => loadedComponent.default);
lazyLoadMonitor.trackComponentLoad(componentName, loadTime);
} catch (error) {
lazyLoadMonitor.trackFailedLoad(componentName, error);
throw error;
} finally {
setLoading(false);
}
}, [componentName, loader, Component]);
return { Component, loading, loadComponent };
}The 2500 ms threshold is the limit of a good LCP score.
Best practices for lazy loading
1. Content prioritization
The most important rule: load what is visible right away immediately, and everything else lazily:
// Above-the-fold content - eager loading
// Below-the-fold content - lazy loading
function ContentStrategy() {
return (
<>
{/* Critical path - eager */}
<Header />
<Hero />
<MainContent />
{/* Secondary content - lazy */}
<Suspense fallback={<SectionSkeleton />}>
<LazySection name="testimonials" />
</Suspense>
<Suspense fallback={<SectionSkeleton />}>
<LazySection name="newsletter" />
</Suspense>
{/* Low priority - very lazy */}
<Suspense fallback={<FooterSkeleton />}>
<LazyFooter />
</Suspense>
</>
);
}The header and the main content do not wait, while the testimonials and the footer arrive in the background.
2. Graceful fallbacks
Lazy loading can fail, for example when the connection drops, so always combine Suspense with an error boundary:
// Always provide graceful fallbacks
function LazyComponentWrapper({ children, fallback, errorFallback }) {
return (
<ErrorBoundary
fallback={errorFallback || <div>An error occurred during loading</div>}
>
<Suspense fallback={fallback || <LoadingSkeleton />}>
{children}
</Suspense>
</ErrorBoundary>
);
}Instead of a blank screen the user sees a skeleton or a clear message.
3. Strategic preloading
Finally, prediction: shortly after the page loads we fetch the components that will probably be needed:
// Strategic preloading based on user behavior
function useStrategicPreloading() {
useEffect(() => {
// Preload 2 seconds after the component mounts
const timeoutId = setTimeout(() => {
// Preload likely next components
import('./components/UserProfile');
import('./components/ShoppingCart');
}, 2000);
// Preload based on mouse movement toward a link
const handleMouseMove = (e) => {
// If cursor is approaching a specific element
// preload the associated component
};
document.addEventListener('mousemove', handleMouseMove);
return () => {
clearTimeout(timeoutId);
document.removeEventListener('mousemove', handleMouseMove);
};
}, []);
}The function returned from useEffect removes the timer and the listener when the component goes away.
Summary
Lazy loading in short:
- Reduces initial bundle size - faster application startup
- Improves Web Vitals - faster FCP and LCP, as long as you do not delay content that is visible right away
- Saves resources - memory, data transfer, battery
- Scales with the application - new features do not grow the startup bundle
- Adapts to conditions - loading tailored to the connection
Lazy loading should be invisible to the user while clearly speeding up the application. It is one of several techniques, next to caching, debouncing (postponing an expensive operation until the user stops typing) and virtual scrolling. Start with splitting by routes because it gives the biggest gain for the smallest cost. In the next lesson you will measure and slim down the bundle itself.
Remember: a visitor does not need maps of the whole island at the gate, only the next map when entering a new sector.
In the preview below, scroll through the dinosaur gallery: the cards load only when they come into view, and the counter shows how many kilobytes have been downloaded so far.
Code for this lesson: lazy-loading-demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lazy Loading - Jurassic Park</title>
<style>
body {
font-family: 'Courier New', monospace;
background: linear-gradient(135deg, #1e3c28 0%, #2d5a3d 100%);
color: #e0e0e0;
margin: 0;
padding: 20px;
}
.header {
text-align: center;
padding: 20px;
background: rgba(0, 0, 0, 0.3);
border-radius: 10px;
margin-bottom: 30px;
}
h1 {
color: #4CAF50;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
max-width: 1200px;
margin: 0 auto;
}
.dino-card {
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
padding: 15px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
transition: transform 0.3s ease;
}
.dino-card:hover {
transform: translateY(-5px);
}
.dino-image {
width: 100%;
height: 200px;
background: linear-gradient(45deg, #2d5a3d 0%, #3d6a4d 100%);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
font-size: 60px;
transition: opacity 0.5s ease;
position: relative;
overflow: hidden;
}
.dino-image.loading {
opacity: 0.5;
}
.dino-image.loaded {
opacity: 1;
background: linear-gradient(45deg, #4CAF50 0%, #45a049 100%);
}
.dino-image::after {
content: 'Loading...';
position: absolute;
bottom: 10px;
font-size: 12px;
color: #fff;
opacity: 0;
transition: opacity 0.3s;
}
.dino-image.loading::after {
opacity: 1;
}
.dino-info {
margin-top: 10px;
}
.dino-name {
font-size: 18px;
font-weight: bold;
color: #4CAF50;
margin-bottom: 5px;
}
.dino-status {
font-size: 14px;
color: #aaa;
}
.stats {
background: rgba(0, 0, 0, 0.3);
padding: 20px;
border-radius: 10px;
margin: 30px auto;
max-width: 600px;
text-align: center;
}
.stat-item {
display: inline-block;
margin: 0 15px;
}
.stat-value {
font-size: 24px;
color: #4CAF50;
font-weight: bold;
}
</style>
</head>
<body>
<div class="header">
<h1>Lazy Loading System - Jurassic Park</h1>
<p>Watch the dinosaurs load on demand!</p>
</div>
<div class="stats" id="stats">
<div class="stat-item">
<div class="stat-value" id="loaded-count">0</div>
<div>Loaded</div>
</div>
<div class="stat-item">
<div class="stat-value" id="total-count">0</div>
<div>Total</div>
</div>
<div class="stat-item">
<div class="stat-value" id="bandwidth-saved">0 KB</div>
<div>Downloaded</div>
</div>
</div>
<div class="gallery" id="gallery"></div>
<script>
console.log('Initializing the Lazy Loading system for Jurassic Park...');
// Dinosaur data
const dinosaurs = [
{ name: 'Tyrannosaurus Rex', emoji: '', species: 'T-Rex', size: 150 },
{ name: 'Velociraptor', emoji: '', species: 'Raptor', size: 80 },
{ name: 'Triceratops', emoji: '', species: 'Herbivore', size: 120 },
{ name: 'Brachiosaurus', emoji: '', species: 'Sauropod', size: 200 },
{ name: 'Stegosaurus', emoji: '', species: 'Herbivore', size: 110 },
{ name: 'Pteranodon', emoji: '', species: 'Flying', size: 90 },
{ name: 'Ankylosaurus', emoji: '', species: 'Armored', size: 130 },
{ name: 'Spinosaurus', emoji: '', species: 'Carnivore', size: 170 },
{ name: 'Parasaurolophus', emoji: '', species: 'Hadrosaur', size: 100 },
{ name: 'Dilophosaurus', emoji: '', species: 'Carnivore', size: 95 }
];
// Statistics
let loadedCount = 0;
let totalBandwidthSaved = 0;
// Class for handling lazy loading
class DinosaurLazyLoader {
constructor() {
this.observer = new IntersectionObserver(
this.handleIntersection.bind(this),
{
root: null,
rootMargin: '100px',
threshold: 0.1
}
);
console.log('Intersection Observer created');
}
handleIntersection(entries) {
entries.forEach(entry => {
if (entry.isIntersecting) {
const card = entry.target;
this.loadDinosaur(card);
this.observer.unobserve(card);
}
});
}
loadDinosaur(card) {
const imageDiv = card.querySelector('.dino-image');
const emoji = card.dataset.emoji;
const size = parseInt(card.dataset.size);
console.log(`Loading dinosaur: ${card.dataset.name}`);
// Simulate loading delay
setTimeout(() => {
imageDiv.textContent = emoji;
imageDiv.classList.remove('loading');
imageDiv.classList.add('loaded');
loadedCount++;
totalBandwidthSaved += size;
this.updateStats();
console.log(`Dinosaur loaded: ${card.dataset.name}`);
}, Math.random() * 500 + 200);
}
updateStats() {
document.getElementById('loaded-count').textContent = loadedCount;
document.getElementById('bandwidth-saved').textContent = totalBandwidthSaved + ' KB';
}
observe(element) {
this.observer.observe(element);
}
}
// Initialization
const loader = new DinosaurLazyLoader();
const gallery = document.getElementById('gallery');
// Creating dinosaur cards
dinosaurs.forEach((dino, index) => {
const card = document.createElement('div');
card.className = 'dino-card';
card.dataset.name = dino.name;
card.dataset.emoji = dino.emoji;
card.dataset.size = dino.size;
card.innerHTML = `
<div class="dino-image loading"></div>
<div class="dino-info">
<div class="dino-name">${dino.name}</div>
<div class="dino-status">Species: ${dino.species} | ID: #${(index + 1).toString().padStart(3, '0')}</div>
</div>
`;
gallery.appendChild(card);
loader.observe(card);
});
// Updating statistics
document.getElementById('total-count').textContent = dinosaurs.length;
console.log(`Created ${dinosaurs.length} dinosaur cards`);
console.log('Scroll the page to watch lazy loading in action!');
console.log('Dinosaurs will load automatically when they enter the viewport');
</script>
</body>
</html>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the main benefit of lazy loading components?
2. What does the dynamic import() expression return in JavaScript?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the stages of lazy loading component configuration:
- Horizontal ordering
Arrange the elements of a dynamic import in the correct order:
- Code editor
The index.js file has a DinosaurAI class with needs (hunger, fatigue, danger on a 0-100 scale) and a decision tree. Fill in the blanks: ___BLANK1___ is the lower limit of a need, below which updateNeed does not lower it, ___BLANK2___ is the array method that goes through the need names and keeps the one with the highest value, and ___BLANK3___ is the comparison operator in decide(): we choose the action of a need only when its value is greater than 30. Danger above 70 always gives 'flee', and when no need exceeds 30, decide() returns 'idle'.
- Click in order
Arrange the elements of subscription in the Observer pattern:
- Code editor
The index.js file has a DataManager class with a Map cache (with a TTL) and storage in localStorage. Fill in the blanks: ___BLANK1___ is the JSON method that turns a value into text before it is stored in localStorage, ___BLANK2___ is the comparison operator that makes get() return the value from the cache only before the expires time, and ___BLANK3___ is the JSON method that turns the text from localStorage back into a value. After an entry expires, get() reads the value from localStorage, for a missing key it returns null, and invalidate removes the key from both places.