Morten Sæther

← Blog

Performance Optimization & Monitoring

#20 · 9 July 2026

Caching, assets, Core Web Vitals, and knowing when it's slow before users tell you

Slow portals lose people. Not dramatically - they just stop coming back and go through the support line instead, which is the cost you built the portal to avoid.

This one’s about making it fast and, more importantly, knowing when it stops being fast. Performance work without monitoring is guesswork with extra steps.

Step by step

1. Cache at every level

Two of the levels are already there, and I don’t write code for them. Power Pages caches the Dataverse data and site configuration it reads on the application server. A record created or updated through the site clears that table’s cache immediately; everything else refreshes within 15 minutes. If I need a configuration change out faster than that, Preview in the design studio or the clear-cache options on /_services/about do it, and that is a tool for quiet hours, not something a script calls.

The CDN is a toggle in the Power Platform admin center. It serves static files by extension (css, js, images, fonts) and whichever anonymous pages I select under Set up > Site performance. It refreshes every hour, I purge it from the admin center after a content change, and authenticated users are always served from the application server. An x-cache: TCP_HIT response header tells me a request came from the edge.

What is left for me is the browser. A small cache in front of my own API calls, with a TTL and a quota guard:

// Browser-side cache: memory first, localStorage for persistence
class BrowserCache {
    constructor(prefix = 'cache:') {
        this.prefix = prefix;
        this.memory = new Map();
    }

    get(key) {
        const entry = this.memory.get(key) || this.readStorage(key);
        if (!entry) return null;
        if (Date.now() >= entry.expiry) {
            this.delete(key);
            return null;
        }
        this.memory.set(key, entry);
        return entry.data;
    }

    set(key, data, ttlSeconds) {
        const entry = { data, expiry: Date.now() + ttlSeconds * 1000 };
        this.memory.set(key, entry);
        if (this.memory.size > 500) {
            this.memory.delete(this.memory.keys().next().value);
        }
        try {
            localStorage.setItem(this.prefix + key, JSON.stringify(entry));
        } catch (error) {
            if (error.name === 'QuotaExceededError') {
                this.evictExpired();
                try {
                    localStorage.setItem(this.prefix + key, JSON.stringify(entry));
                } catch {
                    // Still full: keep it in memory only
                }
            }
        }
    }

    delete(key) {
        this.memory.delete(key);
        localStorage.removeItem(this.prefix + key);
    }

    readStorage(key) {
        try {
            const raw = localStorage.getItem(this.prefix + key);
            return raw ? JSON.parse(raw) : null;
        } catch {
            return null;
        }
    }

    evictExpired() {
        const now = Date.now();
        for (let i = localStorage.length - 1; i >= 0; i--) {
            const storageKey = localStorage.key(i);
            if (!storageKey?.startsWith(this.prefix)) continue;
            try {
                const entry = JSON.parse(localStorage.getItem(storageKey));
                if (!entry || now >= entry.expiry) localStorage.removeItem(storageKey);
            } catch {
                localStorage.removeItem(storageKey);
            }
        }
    }
}

localStorage is shared by everything on the origin and the quota is about 5 MB, so I keep entries small and handle QuotaExceededError instead of planning around it. There is no CDN API or cache-warming endpoint for the browser to call, so this is the whole thing.

2. Sort out your assets

Images are almost always the biggest win, and almost always the last thing anyone looks at:

// Lazy image loader with responsive sources
class ImageLoader {
    // buildUrl(src, { width }) returns the URL of a resized variant
    constructor(buildUrl) {
        this.buildUrl = buildUrl;
        this.observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    this.load(entry.target);
                    this.observer.unobserve(entry.target);
                }
            });
        }, {
            rootMargin: '50px' // Start loading 50px before the image enters the viewport
        });
    }

    // placeholder: an element with data-src, data-alt and optional data-widths="480,960,1440"
    observe(placeholder) {
        this.observer.observe(placeholder);
    }

    load(placeholder) {
        const src = placeholder.dataset.src;
        const img = document.createElement('img');
        img.alt = placeholder.dataset.alt || '';
        img.style.opacity = '0';
        img.style.transition = 'opacity 0.3s ease-in-out';

        const node = placeholder.dataset.widths
            ? this.wrapInPicture(img, src, placeholder.dataset.widths.split(',').map(Number))
            : img;

        img.onload = () => {
            placeholder.replaceWith(node);
            requestAnimationFrame(() => {
                img.style.opacity = '1';
            });
        };

        img.onerror = () => {
            placeholder.classList.add('image-error');
            placeholder.textContent = 'Image unavailable';
        };

        img.src = src;
    }

    wrapInPicture(img, src, widths) {
        const picture = document.createElement('picture');
        const source = document.createElement('source');
        source.srcset = widths
            .map(width => `${this.buildUrl(src, { width })} ${width}w`)
            .join(', ');
        source.sizes = '(max-width: 768px) 100vw, 1180px';
        picture.appendChild(source);
        picture.appendChild(img);
        return picture;
    }
}

// Works with any image service that accepts a width parameter
const loader = new ImageLoader((src, { width }) => `${src}?width=${width}`);
document.querySelectorAll('.lazy-image').forEach(el => loader.observe(el));

The resize service and format negotiation (AVIF, WebP) are the parts this leaves out; both belong to whatever sits in front of your image files, not to the page script.

3. Monitor it for real

Core Web Vitals are LCP, INP and CLS. INP replaced FID as the interactivity metric, and the target is 200 ms or less.

// Real user monitoring: Core Web Vitals, long tasks, slow resources
class PerformanceMonitor {
    constructor(config = {}) {
        this.reportingEndpoint = config.reportingEndpoint;
        this.slowResource = config.slowResource || 1000;
        this.listeners = new Map();
        this.metrics = new Map();
        this.observers = [];

        if (!('PerformanceObserver' in window)) return;
        this.observeLCP();
        this.observeINP();
        this.observeCLS();
        this.observeLongTasks();
        this.observeResources();
        this.startReporting();
    }

    on(name, handler) {
        if (!this.listeners.has(name)) this.listeners.set(name, []);
        this.listeners.get(name).push(handler);
    }

    observe(type, callback, extra = {}) {
        try {
            const observer = new PerformanceObserver(list => callback(list.getEntries()));
            observer.observe({ type, buffered: true, ...extra });
            this.observers.push(observer);
        } catch {
            // Entry type not supported in this browser
        }
    }

    observeLCP() {
        this.observe('largest-contentful-paint', entries => {
            const last = entries[entries.length - 1];
            this.record('lcp', last.startTime, { element: last.element?.tagName });
        });
    }

    // Interaction to Next Paint: the slowest interaction seen so far.
    // The official metric uses a high percentile; the worst case is close enough for alerting.
    observeINP() {
        let worst = 0;
        this.observe('event', entries => {
            entries.forEach(entry => {
                if (entry.interactionId && entry.duration > worst) {
                    worst = entry.duration;
                    this.record('inp', worst, { eventType: entry.name });
                }
            });
        }, { durationThreshold: 40 });
    }

    observeCLS() {
        let clsValue = 0;
        let sessionValue = 0;
        let sessionEntries = [];

        this.observe('layout-shift', entries => {
            entries.forEach(entry => {
                // Only count layout shifts without recent user input
                if (entry.hadRecentInput) return;

                const first = sessionEntries[0];
                const last = sessionEntries[sessionEntries.length - 1];

                // Same session if less than 1s after the previous shift
                // and less than 5s after the first one
                if (sessionValue &&
                    entry.startTime - last.startTime < 1000 &&
                    entry.startTime - first.startTime < 5000) {
                    sessionValue += entry.value;
                    sessionEntries.push(entry);
                } else {
                    sessionValue = entry.value;
                    sessionEntries = [entry];
                }

                if (sessionValue > clsValue) {
                    clsValue = sessionValue;
                    this.record('cls', clsValue, { entries: sessionEntries.length });
                }
            });
        });
    }

    observeLongTasks() {
        this.observe('longtask', entries => {
            entries.forEach(entry => {
                this.record('long_task', entry.duration, { startTime: entry.startTime });
            });
        });
    }

    observeResources() {
        this.observe('resource', entries => {
            entries.forEach(entry => {
                this.record('resource', entry.duration, {
                    name: entry.name,
                    type: entry.initiatorType,
                    size: entry.transferSize
                });
            });
        });
    }

    record(name, value, extra = {}) {
        const metric = { name, value, rating: this.rate(name, value), timestamp: Date.now(), ...extra };

        if (!this.metrics.has(name)) this.metrics.set(name, []);
        const entries = this.metrics.get(name);
        entries.push(metric);
        if (entries.length > 1000) entries.shift();

        (this.listeners.get(name) || []).forEach(handler => handler(metric));
        if (metric.rating === 'poor') {
            (this.listeners.get('alert') || []).forEach(handler => handler(metric));
        }
    }

    rate(name, value) {
        switch (name) {
            case 'lcp': return value <= 2500 ? 'good' : value <= 4000 ? 'needs-improvement' : 'poor';
            case 'inp': return value <= 200 ? 'good' : value <= 500 ? 'needs-improvement' : 'poor';
            case 'cls': return value <= 0.1 ? 'good' : value <= 0.25 ? 'needs-improvement' : 'poor';
            case 'resource': return value <= this.slowResource ? 'good' : 'poor';
            default: return 'n/a';
        }
    }

    startReporting() {
        if (!this.reportingEndpoint) return;

        setInterval(() => this.send(), 60000);

        // Flush when the tab is hidden; more reliable than beforeunload
        document.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'hidden') this.send(true);
        });
    }

    send(unloading = false) {
        const report = { url: location.href, timestamp: Date.now(), metrics: {} };

        this.metrics.forEach((entries, name) => {
            const values = entries.map(e => e.value).sort((a, b) => a - b);
            report.metrics[name] = {
                count: values.length,
                p75: values[Math.floor(values.length * 0.75)],
                max: values[values.length - 1],
                latest: entries[entries.length - 1]
            };
        });

        const body = JSON.stringify(report);

        if (unloading && navigator.sendBeacon) {
            navigator.sendBeacon(this.reportingEndpoint, body);
        } else {
            fetch(this.reportingEndpoint, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body,
                keepalive: true
            }).catch(error => console.error('Performance report failed:', error));
        }

        this.metrics.clear();
    }
}

reportingEndpoint is whatever collects telemetry for you; if that is Application Insights, send through its SDK instead of this send method.

Real user monitoring beats synthetic tests. Your laptop on office wifi is not the phone on a train that your users are holding.

What this looks like in practice

A performance dashboard:

<!-- performance-dashboard.html -->
<div class="performance-dashboard">
    <!-- Core Web Vitals Overview -->
    <div class="core-vitals-section">
        <h2>Core Web Vitals</h2>

        <div class="vitals-grid">
            <div class="vital-card lcp">
                <h3>Largest Contentful Paint</h3>
                <div class="vital-value" id="lcp-value">--</div>
                <div class="vital-rating" id="lcp-rating">measuring...</div>
            </div>

            <div class="vital-card inp">
                <h3>Interaction to Next Paint</h3>
                <div class="vital-value" id="inp-value">--</div>
                <div class="vital-rating" id="inp-rating">measuring...</div>
            </div>

            <div class="vital-card cls">
                <h3>Cumulative Layout Shift</h3>
                <div class="vital-value" id="cls-value">--</div>
                <div class="vital-rating" id="cls-rating">measuring...</div>
            </div>
        </div>
    </div>

    <!-- Loading and resource metrics -->
    <div class="performance-metrics-section">
        <h3>Loading Performance</h3>
        <div class="metric-item">
            <span class="metric-label">Time to First Byte</span>
            <span class="metric-value" id="ttfb-value">--</span>
        </div>
        <div class="metric-item">
            <span class="metric-label">DOM Content Loaded</span>
            <span class="metric-value" id="dcl-value">--</span>
        </div>
        <div class="metric-item">
            <span class="metric-label">Page Load Complete</span>
            <span class="metric-value" id="load-value">--</span>
        </div>
        <div class="metric-item">
            <span class="metric-label">Long Tasks</span>
            <span class="metric-value" id="long-tasks">0</span>
        </div>
        <div class="metric-item">
            <span class="metric-label">Slow Resources</span>
            <span class="metric-value" id="slow-resources">0</span>
        </div>
    </div>

    <!-- Performance Insights -->
    <div class="performance-insights-section">
        <h3>Performance Insights</h3>
        <div id="insights-container"></div>
    </div>
</div>

<script>
    // Performance Dashboard Implementation
    class PerformanceDashboard {
        constructor() {
            this.longTasks = 0;
            this.slowResources = 0;
            this.shownInsights = new Set();

            this.monitor = new PerformanceMonitor({
                reportingEndpoint: null, // set to the endpoint that collects your telemetry
                slowResource: 1000
            });

            this.setupMetricListeners();
            window.addEventListener('load', () => this.updateLoadingMetrics());
        }

        setupMetricListeners() {
            ['lcp', 'inp', 'cls'].forEach(name => {
                this.monitor.on(name, metric => this.updateVital(name, metric));
            });

            this.monitor.on('long_task', () => {
                this.longTasks++;
                document.getElementById('long-tasks').textContent = String(this.longTasks);
            });

            this.monitor.on('resource', metric => {
                if (metric.rating === 'poor') {
                    this.slowResources++;
                    document.getElementById('slow-resources').textContent = String(this.slowResources);
                }
            });
        }

        updateVital(name, metric) {
            document.getElementById(`${name}-value`).textContent = this.formatVitalValue(name, metric.value);
            const rating = document.getElementById(`${name}-rating`);
            rating.textContent = metric.rating;
            rating.className = `vital-rating ${metric.rating}`;

            if (metric.rating === 'poor') {
                this.showInsight(name);
            }
        }

        formatVitalValue(name, value) {
            return name === 'cls' ? value.toFixed(3) : `${Math.round(value)}ms`;
        }

        updateLoadingMetrics() {
            const nav = performance.getEntriesByType('navigation')[0];
            if (!nav) return;

            document.getElementById('ttfb-value').textContent = `${Math.round(nav.responseStart)}ms`;
            document.getElementById('dcl-value').textContent = `${Math.round(nav.domContentLoadedEventEnd)}ms`;
            document.getElementById('load-value').textContent = `${Math.round(nav.loadEventEnd)}ms`;
        }

        showInsight(name) {
            if (this.shownInsights.has(name)) return;
            this.shownInsights.add(name);

            const insights = {
                lcp: {
                    title: 'Slow Largest Contentful Paint',
                    description: 'LCP is above 4 seconds. Look at image sizes and server response time first.',
                    recommendations: [
                        'Serve critical images in modern formats (WebP, AVIF)',
                        'Lazy-load images below the fold',
                        'Remove unused CSS and JavaScript'
                    ]
                },
                inp: {
                    title: 'Slow Interaction to Next Paint',
                    description: 'Users wait too long after clicking or typing. Heavy JavaScript on the main thread is the usual cause.',
                    recommendations: [
                        'Break up long-running JavaScript tasks',
                        'Move heavy computation to web workers',
                        'Defer third-party scripts'
                    ]
                },
                cls: {
                    title: 'Layout Instability Detected',
                    description: 'Elements shift during page load.',
                    recommendations: [
                        'Set explicit dimensions for images and videos',
                        'Reserve space for content that loads late',
                        'Avoid inserting content above existing content'
                    ]
                }
            };

            const insight = insights[name];
            const card = document.createElement('div');
            card.className = 'insight-card warning';

            const title = document.createElement('h4');
            title.textContent = insight.title;
            card.appendChild(title);

            const description = document.createElement('p');
            description.className = 'insight-description';
            description.textContent = insight.description;
            card.appendChild(description);

            const list = document.createElement('ul');
            insight.recommendations.forEach(text => {
                const item = document.createElement('li');
                item.textContent = text;
                list.appendChild(item);
            });
            card.appendChild(list);

            const dismiss = document.createElement('button');
            dismiss.className = 'btn btn-sm btn-outline-primary';
            dismiss.textContent = 'Dismiss';
            dismiss.addEventListener('click', () => card.remove());
            card.appendChild(dismiss);

            document.getElementById('insights-container').appendChild(card);
        }
    }

    // Initialize performance dashboard when DOM is ready
    document.addEventListener('DOMContentLoaded', function() {
        window.performanceDashboard = new PerformanceDashboard();
    });
</script>

How to make a mess and fix it

  1. Slow first load - prioritise critical resources and kill the render-blocking ones
  2. Memory climbing - look at your JavaScript execution and what you’re holding references to
  3. Layout jumping around - set explicit dimensions and reserve space for content that loads late
  4. Cache misses everywhere - revisit the strategy, consider pre-loading
  5. Fine on desktop, bad on mobile - adaptive loading based on device and network

Five habits worth keeping

  1. Load what matters first - resource hints and preloading
  2. Build a baseline that works everywhere, then enhance
  3. Adapt to the device and connection you’re on
  4. Let the data drive optimisation rather than intuition
  5. Set a performance budget and enforce it during development, not after

Wrapping up

Performance isn’t a task you finish - it’s a property you maintain. Watch Core Web Vitals, cache at several levels, optimise assets for the range of devices you serve, and keep real-time visibility so problems surface before your users report them.

That’s the advanced customisation section done. Next section: pro-code development, custom components, and enterprise integration.