Performance: Frontend Monitoring
Relevant source files
The following files were used as context for generating this wiki page:- themes/matrix-flow/source/js/performance-monitor.js
- themes/matrix-flow/tests/fullscreen-layout-performance.test.js
- themes/matrix-flow/source/js/code-splitter.js
- themes/matrix-flow/scripts/critical-css-extractor.js
- themes/matrix-flow/scripts/css-optimizer.js
- themes/matrix-flow/scripts/critical-css.js
- themes/matrix-flow/CSS-INTEGRATION-README.md
The Frontend Performance Monitoring system, encapsulated within the PerformanceMonitor class, is a crucial component of the Matrix Flow theme designed to track, measure, and validate the website's performance in real-time. Its primary purpose is to collect a wide range of metrics, including standard navigation and resource timings, Core Web Vitals (LCP, FID, CLS), and custom application-specific timings.
This system provides developers with actionable insights by generating comprehensive reports that include automated recommendations for improvement. It plays a key role in verifying the effectiveness of performance optimizations such as critical CSS inlining and JavaScript code splitting. All reports are stored locally in the browser's localStorage for debugging and analysis.
Sources: themes/matrix-flow/source/js/performance-monitor.js
Architecture and Initialization
The monitoring system is built around the PerformanceMonitor class. An instance of this class is created and attached to the window object upon the DOMContentLoaded event, ensuring that monitoring begins as early as possible in the page lifecycle.
Sources: themes/matrix-flow/source/js/performance-monitor.js:308-310
PerformanceMonitor Class Structure
The diagram below illustrates the main components and methods of the PerformanceMonitor class.
This diagram shows the key properties and methods within the PerformanceMonitor class.
Sources: themes/matrix-flow/source/js/performance-monitor.js:6-15
Initialization Flow
The monitoring process is initiated when the DOM is fully loaded. The init() method sets up event listeners for both DOMContentLoaded and the full page load event to collect metrics at different stages of the page lifecycle.
This sequence diagram details the initialization and metric collection timeline of the PerformanceMonitor.
Sources: themes/matrix-flow/source/js/performance-monitor.js:17-28, themes/matrix-flow/source/js/performance-monitor.js:192-197
Core Web Vitals and Key Metrics Collection
The system collects a variety of metrics using the window.performance API and PerformanceObserver to provide a holistic view of the user experience.
Navigation Timing
The collectNavigationTiming method gathers key page load timings from performance.timing.
| Metric | Description | Calculation |
|---|---|---|
dnsLookup | Time spent on DNS lookup. | timing.domainLookupEnd - timing.domainLookupStart |
tcpConnection | Time spent establishing the TCP connection. | timing.connectEnd - timing.connectStart |
ttfb | Time to First Byte. | timing.responseStart - timing.navigationStart |
request | Time for the browser to request the page. | timing.responseStart - timing.requestStart |
response | Time to download the response. | timing.responseEnd - timing.responseStart |
domProcessing | Time to parse the DOM. | timing.domComplete - timing.domLoading |
domContentLoaded | Time until the DOMContentLoaded event fires. | timing.domContentLoadedEventEnd - timing.navigationStart |
totalLoad | Total time for the page to load completely. | timing.loadEventEnd - timing.navigationStart |
Sources: themes/matrix-flow/source/js/performance-monitor.js:36-62
Resource Timing
The collectResourceTiming method analyzes all resources loaded on the page, grouping them by type (CSS, JavaScript, image, etc.) and calculating their collective impact.
The data is stored in metrics.resourceSizes with the following structure for each resource type:
{
"css": {
"count": 2,
"totalSize": 15000,
"totalDuration": 250,
"resources": [
{
"name": "/css/style.css",
"size": 15000,
"duration": 200,
"cached": false
}
]
}
}
Sources: themes/matrix-flow/source/js/performance-monitor.js:64-98
Critical Path Metrics
To validate rendering optimizations, collectCriticalPathMetrics measures:
- Critical CSS Size: The character length of the inline
<style>tag. - Render-Blocking Resources: The number of synchronous CSS (
<link rel="stylesheet">) and JavaScript (<script>) tags in the head. - First Paint (FP) and First Contentful Paint (FCP): The timestamps for these paint events.
This directly measures the effectiveness of strategies defined in critical-css-extractor.js.
Sources: themes/matrix-flow/source/js/performance-monitor.js:114-135, themes/matrix-flow/scripts/critical-css-extractor.js
Core Web Vitals
Core Web Vitals are collected using a PerformanceObserver to measure user-centric metrics. The system targets specific thresholds for a good user experience, as defined in performance tests.
| Vital | Description | Target Threshold |
|---|---|---|
| LCP (Largest Contentful Paint) | Measures loading performance. | < 2500ms |
| FID (First Input Delay) | Measures interactivity. | < 100ms |
| CLS (Cumulative Layout Shift) | Measures visual stability. | < 0.1 |
Sources: themes/matrix-flow/source/js/performance-monitor.js:199-239, themes/matrix-flow/tests/fullscreen-layout-performance.test.js:600-606
User and Module Timing
The system extends beyond standard metrics to capture custom application events and module load times, providing deeper insights into the performance of specific features.
Custom User Timings
The startUserTimingCollection method uses performance.mark() to create custom markers for significant events during the application's lifecycle. This allows for precise measurement of feature-specific operations.
Key custom marks include:
matrix-animation-startlazy-loader-initnewsletter-widget-ready
Sources: themes/matrix-flow/source/js/performance-monitor.js:137-142
Module Load Performance
The performance monitor integrates with the CodeSplitter module to measure the load time of dynamically imported JavaScript modules. It wraps the moduleLoader.loadModule function to automatically mark the start and end of each module load, then uses performance.measure() to calculate the duration.
This diagram shows how the PerformanceMonitor measures the load time of a module requested by the CodeSplitter.
Sources: themes/matrix-flow/source/js/performance-monitor.js:145-165, themes/matrix-flow/source/js/code-splitter.js:114-142
Reporting and Recommendations
A key feature of the monitoring system is its ability to generate a summary report with automated, actionable recommendations.
Performance Report Generation
The generateReport() method compiles all collected metrics into a single JSON object. This report includes the timestamp, URL, user agent, all collected metrics, and a list of recommendations. The report is then stored in localStorage under the key performanceReports.
A sample report structure is as follows:
{
"timestamp": "2023-10-27T10:00:00.000Z",
"url": "http://localhost:4000/",
"userAgent": "...",
"metrics": {
"loadTimes": { "...": "..." },
"resourceSizes": { "...": "..." },
"criticalPath": { "...": "..." },
"userTiming": { "...": "..." }
},
"recommendations": [
"Server response time could be improved (TTFB >800ms)"
]
}
Sources: themes/matrix-flow/source/js/performance-monitor.js:254-267, themes/matrix-flow/source/js/performance-monitor.js:295-306
Automated Recommendations
The generateRecommendations() method analyzes the collected metrics against predefined thresholds to suggest potential optimizations.
| Trigger Condition | Recommendation Message |
|---|---|
totalLoad > 3000 | "Consider optimizing total page load time (>3s)" |
ttfb > 800 | "Server response time could be improved (TTFB >800ms)" |
CSS totalSize > 50000 | "CSS bundle size is large, consider code splitting" |
JavaScript totalSize > 100000 | "JavaScript bundle size is large, consider code splitting" |
renderBlockingCSS > 2 | "Too many render-blocking CSS files" |
renderBlockingJS > 1 | "Consider making JavaScript non-render-blocking" |
Sources: themes/matrix-flow/source/js/performance-monitor.js:269-293
Integration with Optimization Strategies
The monitoring system is designed to work in concert with the theme's build-time and runtime optimization strategies, providing a feedback loop to validate their effectiveness.
Critical CSS
The theme employs scripts like critical-css-extractor.js and css-optimizer.js to extract above-the-fold CSS and inline it, reducing render-blocking requests. The PerformanceMonitor validates this by:
- Measuring the size of the inlined critical CSS (
metrics.criticalPath.criticalCSSSize). - Counting the number of remaining render-blocking CSS files (
metrics.criticalPath.renderBlockingCSS). - Measuring the First Contentful Paint (FCP) time, which should be improved by this strategy.
Sources: themes/matrix-flow/source/js/performance-monitor.js:114-135, themes/matrix-flow/scripts/critical-css-extractor.js:10-16, themes/matrix-flow/scripts/css-optimizer.js:71-76
Code Splitting and Lazy Loading
The CodeSplitter module dynamically loads JavaScript based on priority, interaction, or viewport visibility. The PerformanceMonitor directly measures the impact of this strategy by timing each module's load. Furthermore, performance tests confirm that IntersectionObserver is used for lazy-loading images, another key optimization tracked by the monitoring system.
Sources: themes/matrix-flow/source/js/performance-monitor.js:145-165, themes/matrix-flow/source/js/code-splitter.js:11-21, themes/matrix-flow/tests/fullscreen-layout-performance.test.js:522-540