Skip to content

Commit 7a4d64a

Browse files
committed
Use the more appropriate ResizeObserver instead of MutationObserver
1 parent cb5bbf6 commit 7a4d64a

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

plugins/optimization-detective/detect.js

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -216,11 +216,11 @@ export default async function detect( {
216216
);
217217

218218
/**
219-
* Monitors embed for mutations.
219+
* Monitors embed wrapper for resizes.
220220
*
221221
* @param {HTMLDivElement} embedWrapper Embed wrapper DIV.
222222
*/
223-
function monitorEmbedForMutations( embedWrapper ) {
223+
function monitorEmbedWrapperForResizes( embedWrapper ) {
224224
// If the embed lacks any scripting, then short-circuit since it can't possibly be doing any mutations.
225225
if ( ! embedWrapper.querySelector( 'script, [onload]' ) ) {
226226
return;
@@ -230,22 +230,27 @@ export default async function detect( {
230230
}
231231
const xpath = embedWrapper.dataset.odXpath;
232232
let timeoutId = 0;
233-
const observer = new MutationObserver( () => {
233+
const observer = new ResizeObserver( ( entries ) => {
234+
const [ entry ] = entries;
234235
if ( timeoutId > 0 ) {
235236
clearTimeout( timeoutId );
236237
}
238+
log(
239+
`[Embed Optimizer] Pending embed height of ${ entry.contentRect.height }px for ${ xpath }`
240+
);
241+
// TODO: Is the timeout really needed? We can just keep updating the height of the element until the URL metrics are sent when the page closes.
237242
timeoutId = setTimeout( () => {
238-
const rect = embedWrapper.getBoundingClientRect();
239243
log(
240-
`[Embed Optimizer] Embed height of ${ rect.height }px for ${ xpath }`
244+
`[Embed Optimizer] Final embed height of ${ entry.contentRect.height }px for ${ xpath }`
241245
);
246+
observer.disconnect();
242247
// TODO: Now amend URL metrics with this rect.height.
243248
}, EMBED_LOAD_WAIT_MS );
244249
} );
245-
observer.observe( embedWrapper, { childList: true, subtree: true } );
250+
observer.observe( embedWrapper, { box: 'content-box' } );
246251
}
247252
for ( const embedWrapper of embedWrappers ) {
248-
monitorEmbedForMutations( embedWrapper );
253+
monitorEmbedWrapperForResizes( embedWrapper );
249254
}
250255

251256
// Wait until the resources on the page have fully loaded.

0 commit comments

Comments
 (0)