Online and Offline Events
You'll learn how to respond automatically when the user's connection drops or recovers using built-in browser events.
The Core Idea
While navigator.onLine (from the previous lesson) lets you check connection status at any moment, the online and offline events let your app react when network status changes. Think of it like the difference between checking your watch versus setting an alarm — one is manual, the other notifies you automatically.
The browser fires an offline event when it loses connectivity and an online event when it reconnects. You can listen to these on the window object and update your UI, queue requests, or warn users immediately.
How It Works
// Listen for connectivity loss
window.addEventListener('offline', () => {
console.log('Connection lost');
document.body.classList.add('offline-mode');
showNotification('You are offline. Changes will sync when reconnected.');
});
// Listen for connectivity restoration
window.addEventListener('online', () => {
console.log('Connection restored');
document.body.classList.remove('offline-mode');
showNotification('Back online!');
syncPendingData(); // Resume queued operations
});
These events complement navigator.onLine perfectly: use the property for initial checks when your page loads, and use the events to react dynamically to changes.
Practical Application
Combine this with retry logic (from earlier lessons) to automatically resume failed requests when connectivity returns:
let pendingRequests = [];
window.addEventListener('online', () => {
pendingRequests.forEach(retryFn => retryFn());
pendingRequests = [];
});
Key Takeaway: The online and offline events on window enable your app to react instantly to network changes, providing responsive feedback and automated recovery without constant polling.