utils.js (2192B)
1 function waitForAnimationFrames(count) { 2 return new Promise(resolve => { 3 if (count-- <= 0) { 4 resolve(); 5 } else { 6 requestAnimationFrame(() => { 7 waitForAnimationFrames(count).then(resolve); 8 }); 9 } 10 }); 11 } 12 13 // Asserts that there is currently no FCP reported. Pass t to add some wait, in case CSS is loaded 14 // and FCP is incorrectly fired afterwards. 15 async function assertNoFirstContentfulPaint(t) { 16 await waitForAnimationFrames(3); 17 assert_equals(performance.getEntriesByName('first-contentful-paint').length, 0, 'First contentful paint marked too early. '); 18 } 19 20 // Function that is resolved once FCP is reported, using PerformanceObserver. It rejects after a long 21 // wait time so that failing tests don't timeout. 22 async function assertFirstContentfulPaint(t) { 23 return new Promise(resolve => { 24 function checkFCP() { 25 const entries = performance.getEntriesByName('first-contentful-paint'); 26 if (entries.length === 1) { 27 resolve(entries[0]); 28 } else { 29 t.step_timeout(checkFCP, 0); 30 } 31 } 32 t.step(checkFCP); 33 }); 34 } 35 36 async function test_fcp(label, before_assert_fcp_func) { 37 setup({"hide_test_state": true}); 38 const style = document.createElement('style'); 39 document.head.appendChild(style); 40 await promise_test(async t => { 41 assert_implements(window.PerformancePaintTiming, "Paint Timing isn't supported."); 42 const main = document.getElementById('main'); 43 await new Promise(r => window.addEventListener('load', r)); 44 await assertNoFirstContentfulPaint(t); 45 main.className = 'preFCP'; 46 await assertNoFirstContentfulPaint(t); 47 const time_before_fcp_func = performance.now(); 48 if (before_assert_fcp_func) { 49 await before_assert_fcp_func(); 50 } 51 main.className = 'contentful'; 52 const entry = await assertFirstContentfulPaint(t); 53 if ("paintTime" in entry) { 54 if ("presentationTime" in entry && entry.presentationTime !== null) { 55 assert_greater_than(entry.presentationTime, entry.paintTime); 56 assert_equals(entry.startTime, entry.presentationTime); 57 } else { 58 assert_equals(entry.startTime, entry.paintTime); 59 } 60 } 61 }, label); 62 }