Note: Differential serving can reduce bundle sizes by 30-50% for modern
browsers while maintaining backward compatibility. Use module/nomodule for automatic detection.
2. Dynamic Import and Code Splitting Strategies
Strategy
Use Case
Loading Time
Implementation
Route-based
Load code per page/route
On navigation
import('./page.js')
Component-based
Lazy load components
On visibility/interaction
React.lazy, Vue async
Vendor chunks
Separate node_modules
Initial load
splitChunks config
Polyfill chunks
Load only if needed
Conditional
Feature detection + import()
Prefetch/Preload
Anticipate future needs
Idle time
<link rel="prefetch">
Example: Conditional polyfill loading
// Load polyfills only when neededasync function loadPolyfills() { var polyfills = []; // Check what's needed if (!('Promise' in window)) { polyfills.push(import('core-js/features/promise')); } if (!('fetch' in window)) { polyfills.push(import('whatwg-fetch')); } if (!('IntersectionObserver' in window)) { polyfills.push(import('intersection-observer')); } if (!window.customElements) { polyfills.push(import('@webcomponents/webcomponentsjs/webcomponents-bundle')); } // Wait for all polyfills to load if (polyfills.length > 0) { await Promise.all(polyfills); console.log('Polyfills loaded:', polyfills.length); }}// Initialize app after polyfillsloadPolyfills() .then(() => { return import('./app.js'); }) .then((app) => { app.init(); }) .catch((error) => { console.error('Failed to load:', error); });// Webpack magic comments for chunk namingasync function loadFeature() { const module = await import( /* webpackChunkName: "heavy-feature" */ /* webpackPrefetch: true */ './heavy-feature.js' ); return module;}
Note: Use multiple CDN fallbacks for reliability. Always include
local fallback and use SRI hashes for security.
5. Service Worker and Offline Polyfill Caching
Strategy
Description
Use Case
Cache Priority
Cache First
Serve from cache, fallback to network
Static polyfills
High
Network First
Try network, fallback to cache
Frequently updated polyfills
Medium
Stale While Revalidate
Serve cache, update in background
Best of both worlds
Balanced
Network Only
Always fetch from network
Development
None
Cache Only
Only serve cached content
Offline-first apps
Required
Example: Service Worker for polyfill caching
// service-worker.jsvar CACHE_NAME = 'polyfills-v1';var POLYFILL_URLS = [ '/polyfills/core-js.min.js', '/polyfills/fetch.min.js', '/polyfills/intersection-observer.min.js', '/polyfills/resize-observer.min.js'];// Install - cache polyfillsself.addEventListener('install', function(event) { event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Caching polyfills'); return cache.addAll(POLYFILL_URLS); }) .then(function() { return self.skipWaiting(); }) );});// Activate - cleanup old cachesself.addEventListener('activate', function(event) { event.waitUntil( caches.keys() .then(function(cacheNames) { return Promise.all( cacheNames.map(function(cacheName) { if (cacheName !== CACHE_NAME) { console.log('Deleting old cache:', cacheName); return caches.delete(cacheName); } }) ); }) .then(function() { return self.clients.claim(); }) );});// Fetch - serve from cache with network fallbackself.addEventListener('fetch', function(event) { var url = new URL(event.request.url); // Only handle polyfill requests if (url.pathname.indexOf('/polyfills/') !== 0) { return; } event.respondWith( caches.match(event.request) .then(function(response) { if (response) { console.log('Serving from cache:', url.pathname); return response; } console.log('Fetching from network:', url.pathname); return fetch(event.request) .then(function(response) { // Cache the new response if (response.status === 200) { var responseClone = response.clone(); caches.open(CACHE_NAME) .then(function(cache) { cache.put(event.request, responseClone); }); } return response; }); }) .catch(function() { console.error('Failed to load:', url.pathname); }) );});// Register service worker (in main app)if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/service-worker.js') .then(function(registration) { console.log('Service Worker registered:', registration); }) .catch(function(error) { console.error('Service Worker registration failed:', error); });}
Example: Stale-while-revalidate strategy
// Advanced caching with stale-while-revalidateself.addEventListener('fetch', function(event) { var url = new URL(event.request.url); if (url.pathname.indexOf('/polyfills/') !== 0) { return; } event.respondWith( caches.open(CACHE_NAME).then(function(cache) { return cache.match(event.request).then(function(cachedResponse) { // Fetch from network in background var fetchPromise = fetch(event.request).then(function(networkResponse) { // Update cache with fresh response if (networkResponse.status === 200) { cache.put(event.request, networkResponse.clone()); } return networkResponse; }); // Return cached response immediately if available // Otherwise wait for network return cachedResponse || fetchPromise; }); }) );});
Note: Service Workers enable offline-first polyfill delivery.
Use cache-first strategy for stable polyfills, network-first for frequently updated ones.