/** * YAZ Care Platform - Performance Optimization Module * Version: 3.8.0 (Sprint 32) * * Features: * - Core Web Vitals monitoring (FCP, LCP, FID, CLS, TTFB) * - Resource hints (preload, prefetch, preconnect) * - Lazy loading for images and components * - Code splitting and dynamic imports * - Resource prioritization * - Performance budgets and alerts * * Standards Compliance: Web.dev Best Practices, Lighthouse Guidelines */ 'use strict'; // Debug-gated logger — only emits in non-production when window.YAZ_DEBUG === true const _log = (typeof window !== 'undefined' && window.YAZ_DEBUG) ? console.log.bind(console) : function () {}; // ============================================================================= // CONFIGURATION // ============================================================================= const PERF_CONFIG = { // Core Web Vitals targets (Google thresholds) targets: { FCP: 1800, // First Contentful Paint <1.8s (good) LCP: 2500, // Largest Contentful Paint <2.5s (good) FID: 100, // First Input Delay <100ms (good) CLS: 0.1, // Cumulative Layout Shift <0.1 (good) TTFB: 800, // Time to First Byte <800ms (good) INP: 200 // Interaction to Next Paint <200ms (good) }, // Performance budgets (in KB) budgets: { javascript: 300, css: 50, images: 500, fonts: 100, total: 1000 }, // Lazy loading settings lazyLoad: { rootMargin: '50px', threshold: 0.01, imagePlaceholder: 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300"%3E%3Crect fill="%23f0f0f0" width="400" height="300"/%3E%3C/svg%3E' }, // Resource hints criticalResources: [ '/static/css/main.css', '/static/js/pwa.js', '/static/js/alpine.js', '/static/js/htmx.min.js' ] }; // ============================================================================= // CORE WEB VITALS MONITOR // ============================================================================= class WebVitalsMonitor { constructor() { this.metrics = {}; this.observers = []; this.init(); } init() { // Check browser support if (!('PerformanceObserver' in window)) { console.warn('[Perf] PerformanceObserver not supported'); return; } this.observePaint(); this.observeLCP(); this.observeFID(); this.observeCLS(); this.observeTTFB(); this.observeINP(); } /** * First Contentful Paint (FCP) */ observePaint() { const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { if (entry.name === 'first-contentful-paint') { this.recordMetric('FCP', entry.startTime); } } }); try { observer.observe({ entryTypes: ['paint'] }); this.observers.push(observer); } catch (e) { console.warn('[Perf] Paint observer failed:', e); } } /** * Largest Contentful Paint (LCP) */ observeLCP() { let lcpValue = 0; const observer = new PerformanceObserver((list) => { const entries = list.getEntries(); const lastEntry = entries[entries.length - 1]; lcpValue = lastEntry.renderTime || lastEntry.loadTime; this.recordMetric('LCP', lcpValue); }); try { observer.observe({ type: 'largest-contentful-paint', buffered: true }); this.observers.push(observer); } catch (e) { console.warn('[Perf] LCP observer failed:', e); } } /** * First Input Delay (FID) */ observeFID() { const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { const delay = entry.processingStart - entry.startTime; this.recordMetric('FID', delay); } }); try { observer.observe({ type: 'first-input', buffered: true }); this.observers.push(observer); } catch (e) { console.warn('[Perf] FID observer failed:', e); } } /** * Cumulative Layout Shift (CLS) */ observeCLS() { let clsValue = 0; const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { if (!entry.hadRecentInput) { clsValue += entry.value; this.recordMetric('CLS', clsValue); } } }); try { observer.observe({ type: 'layout-shift', buffered: true }); this.observers.push(observer); } catch (e) { console.warn('[Perf] CLS observer failed:', e); } } /** * Time to First Byte (TTFB) */ observeTTFB() { const observer = new PerformanceObserver((list) => { const entries = list.getEntries(); if (entries.length > 0) { const navigationEntry = entries[0]; const ttfb = navigationEntry.responseStart - navigationEntry.requestStart; this.recordMetric('TTFB', ttfb); } }); try { observer.observe({ type: 'navigation', buffered: true }); this.observers.push(observer); } catch (e) { console.warn('[Perf] TTFB observer failed:', e); } } /** * Interaction to Next Paint (INP) */ observeINP() { let maxINP = 0; const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { const inp = entry.processingStart - entry.startTime + entry.duration; if (inp > maxINP) { maxINP = inp; this.recordMetric('INP', maxINP); } } }); try { observer.observe({ type: 'event', buffered: true }); this.observers.push(observer); } catch (e) { console.warn('[Perf] INP observer failed:', e); } } /** * Record metric and evaluate against target */ recordMetric(name, value) { this.metrics[name] = value; const target = PERF_CONFIG.targets[name]; const status = value <= target ? 'good' : 'needs-improvement'; _log( `[Perf] ${name}: ${value.toFixed(2)}ms ${status === 'good' ? '✅' : '⚠️'} ` + `(target: ${target}ms)` ); // Send to analytics this.sendMetricToAnalytics(name, value, status); // Show warning if exceeds target if (status !== 'good') { this.showPerformanceWarning(name, value, target); } } sendMetricToAnalytics(name, value, status) { if (typeof gtag !== 'undefined') { gtag('event', 'web_vitals', { event_category: 'Performance', event_label: name, value: Math.round(value), metric_status: status }); } } showPerformanceWarning(name, value, target) { const exceeded = ((value - target) / target * 100).toFixed(1); console.warn( `[Perf] ${name} exceeded target by ${exceeded}% ` + `(${value.toFixed(2)}ms vs ${target}ms)` ); } getMetrics() { return { ...this.metrics }; } disconnect() { this.observers.forEach(observer => observer.disconnect()); this.observers = []; } } // ============================================================================= // RESOURCE OPTIMIZER // ============================================================================= class ResourceOptimizer { constructor() { this.resourceMap = new Map(); } /** * Add resource hints to improve loading performance */ addResourceHints() { // Fonts and vendors are self-hosted — no external preconnects needed. // Preload critical local resources PERF_CONFIG.criticalResources.forEach(resource => { this.preload(resource); }); _log('[Perf] Resource hints added'); } preconnect(url) { const link = document.createElement('link'); link.rel = 'preconnect'; link.href = url; link.crossOrigin = 'anonymous'; document.head.appendChild(link); } preload(url) { const link = document.createElement('link'); link.rel = 'preload'; link.href = url; link.as = this.getResourceType(url); document.head.appendChild(link); } prefetch(url) { const link = document.createElement('link'); link.rel = 'prefetch'; link.href = url; document.head.appendChild(link); } getResourceType(url) { if (url.endsWith('.css')) return 'style'; if (url.endsWith('.js')) return 'script'; if (url.match(/\.(woff2?|ttf|eot)$/)) return 'font'; if (url.match(/\.(png|jpg|jpeg|gif|webp|svg)$/)) return 'image'; return 'fetch'; } /** * Defer non-critical resources */ deferNonCriticalResources() { // Defer non-critical CSS const stylesheets = document.querySelectorAll('link[rel="stylesheet"]:not([data-critical])'); stylesheets.forEach(link => { link.media = 'print'; link.onload = function () { this.media = 'all'; }; }); // Defer non-critical scripts const scripts = document.querySelectorAll('script:not([data-critical])'); scripts.forEach(script => { if (!script.async && !script.defer) { script.defer = true; } }); _log('[Perf] Non-critical resources deferred'); } } // ============================================================================= // LAZY LOADING MANAGER // ============================================================================= class LazyLoadManager { constructor() { this.observer = null; this.init(); } init() { if (!('IntersectionObserver' in window)) { console.warn('[Perf] IntersectionObserver not supported, loading all images'); this.loadAllImages(); return; } const options = { root: null, rootMargin: PERF_CONFIG.lazyLoad.rootMargin, threshold: PERF_CONFIG.lazyLoad.threshold }; this.observer = new IntersectionObserver( (entries) => this.handleIntersection(entries), options ); this.observeImages(); this.observeComponents(); _log('[Perf] Lazy loading initialized'); } handleIntersection(entries) { entries.forEach(entry => { if (entry.isIntersecting) { const element = entry.target; if (element.tagName === 'IMG') { this.loadImage(element); } else { this.loadComponent(element); } this.observer.unobserve(element); } }); } observeImages() { const images = document.querySelectorAll('img[data-src]'); images.forEach(img => { // Set placeholder if (!img.src) { img.src = PERF_CONFIG.lazyLoad.imagePlaceholder; } this.observer.observe(img); }); } observeComponents() { const components = document.querySelectorAll('[data-lazy-component]'); components.forEach(component => this.observer.observe(component)); } loadImage(img) { const src = img.dataset.src; const srcset = img.dataset.srcset; if (src) { img.src = src; img.removeAttribute('data-src'); } if (srcset) { img.srcset = srcset; img.removeAttribute('data-srcset'); } img.classList.add('loaded'); } loadComponent(component) { const componentName = component.dataset.lazyComponent; const componentUrl = component.dataset.componentUrl; if (componentUrl) { fetch(componentUrl) .then(response => response.text()) .then(html => { component.innerHTML = html; component.removeAttribute('data-lazy-component'); component.classList.add('loaded'); }) .catch(error => { console.error(`[Perf] Failed to load component ${componentName}:`, error); }); } } loadAllImages() { const images = document.querySelectorAll('img[data-src]'); images.forEach(img => this.loadImage(img)); } disconnect() { if (this.observer) { this.observer.disconnect(); } } } // ============================================================================= // PERFORMANCE BUDGET MONITOR // ============================================================================= class BudgetMonitor { constructor() { this.budgets = PERF_CONFIG.budgets; this.usage = {}; } async checkBudgets() { const resources = performance.getEntriesByType('resource'); // Calculate usage by type this.usage = { javascript: 0, css: 0, images: 0, fonts: 0, total: 0 }; resources.forEach(resource => { const size = resource.transferSize || 0; const sizeKB = size / 1024; this.usage.total += sizeKB; if (resource.name.endsWith('.js')) { this.usage.javascript += sizeKB; } else if (resource.name.endsWith('.css')) { this.usage.css += sizeKB; } else if (resource.name.match(/\.(png|jpg|jpeg|gif|webp|svg)$/)) { this.usage.images += sizeKB; } else if (resource.name.match(/\.(woff2?|ttf|eot)$/)) { this.usage.fonts += sizeKB; } }); // Check against budgets Object.keys(this.budgets).forEach(type => { const budget = this.budgets[type]; const usage = this.usage[type]; const percent = (usage / budget * 100).toFixed(1); const status = usage <= budget ? '✅' : '⚠️'; _log( `[Perf] Budget ${type}: ${usage.toFixed(1)}KB / ${budget}KB ` + `(${percent}%) ${status}` ); if (usage > budget) { console.warn( `[Perf] Budget exceeded for ${type}: ` + `${usage.toFixed(1)}KB > ${budget}KB` ); } }); return this.usage; } } // ============================================================================= // CODE SPLITTING HELPER // ============================================================================= class CodeSplitter { constructor() { this.loadedModules = new Set(); } /** * Dynamically import module when needed */ async loadModule(moduleName) { if (this.loadedModules.has(moduleName)) { _log(`[Perf] Module ${moduleName} already loaded`); return; } try { const module = await import(`/static/js/${moduleName}.js`); this.loadedModules.add(moduleName); _log(`[Perf] Module ${moduleName} loaded`); return module; } catch (error) { console.error(`[Perf] Failed to load module ${moduleName}:`, error); throw error; } } /** * Preload module for future use */ preloadModule(moduleName) { const link = document.createElement('link'); link.rel = 'modulepreload'; link.href = `/static/js/${moduleName}.js`; document.head.appendChild(link); } } // ============================================================================= // PERFORMANCE MANAGER (MAIN CLASS) // ============================================================================= class PerformanceManager { constructor() { this.vitalsMonitor = new WebVitalsMonitor(); this.resourceOptimizer = new ResourceOptimizer(); this.lazyLoadManager = new LazyLoadManager(); this.budgetMonitor = new BudgetMonitor(); this.codeSplitter = new CodeSplitter(); this.init(); } init() { _log('[Perf] Performance optimization initialized'); // Add resource hints this.resourceOptimizer.addResourceHints(); // Defer non-critical resources this.resourceOptimizer.deferNonCriticalResources(); // Check budgets after page load window.addEventListener('load', () => { setTimeout(() => { this.budgetMonitor.checkBudgets(); }, 3000); }); } getReport() { return { vitals: this.vitalsMonitor.getMetrics(), budgets: this.budgetMonitor.usage, timestamp: new Date().toISOString() }; } } // ============================================================================= // EXPORT // ============================================================================= // Create global instance window.Performance = new PerformanceManager(); _log('[Perf] Performance module loaded');