@@ -19,11 +19,50 @@ function returnError(errorMessage) {
1919 return { error : errorMessage , success : false } ;
2020}
2121
22+ /**
23+ * @returns {Promise<number | null> }
24+ */
25+ function waitForLCP ( timeoutMs = 500 ) {
26+ return new Promise ( ( resolve ) => {
27+ let timeoutId ;
28+ let observer ;
29+
30+ const cleanup = ( ) => {
31+ if ( observer ) observer . disconnect ( ) ;
32+ if ( timeoutId ) clearTimeout ( timeoutId ) ;
33+ } ;
34+
35+ // Set timeout
36+ timeoutId = setTimeout ( ( ) => {
37+ cleanup ( ) ;
38+ resolve ( null ) ; // Resolve with null instead of hanging
39+ } , timeoutMs ) ;
40+
41+ // Try to get existing LCP
42+ observer = new PerformanceObserver ( ( list ) => {
43+ const entries = list . getEntries ( ) ;
44+ const lastEntry = entries [ entries . length - 1 ] ;
45+ if ( lastEntry ) {
46+ cleanup ( ) ;
47+ resolve ( lastEntry . startTime ) ;
48+ }
49+ } ) ;
50+
51+ try {
52+ observer . observe ( { type : 'largest-contentful-paint' , buffered : true } ) ;
53+ } catch ( error ) {
54+ // Handle browser compatibility issues
55+ cleanup ( ) ;
56+ resolve ( null ) ;
57+ }
58+ } ) ;
59+ }
60+
2261/**
2362 * Get the expanded performance metrics
24- * @returns {ErrorObject | PerformanceMetricsResponse }
63+ * @returns {Promise< ErrorObject | PerformanceMetricsResponse> }
2564 */
26- export function getExpandedPerformanceMetrics ( ) {
65+ export async function getExpandedPerformanceMetrics ( ) {
2766 try {
2867 if ( document . readyState !== 'complete' ) {
2968 return returnError ( 'Document not ready' ) ;
@@ -38,15 +77,8 @@ export function getExpandedPerformanceMetrics() {
3877
3978 // Get largest contentful paint if available
4079 let largestContentfulPaint = null ;
41- if (
42- window . PerformanceObserver &&
43- PerformanceObserver . supportedEntryTypes &&
44- PerformanceObserver . supportedEntryTypes . includes ( 'largest-contentful-paint' )
45- ) {
46- const lcpEntries = performance . getEntriesByType ( 'largest-contentful-paint' ) ;
47- if ( lcpEntries . length > 0 ) {
48- largestContentfulPaint = lcpEntries [ lcpEntries . length - 1 ] . startTime ;
49- }
80+ if ( PerformanceObserver . supportedEntryTypes . includes ( 'largest-contentful-paint' ) ) {
81+ largestContentfulPaint = await waitForLCP ( ) ;
5082 }
5183
5284 // Calculate total resource sizes
0 commit comments