Skip to content

Commit

Permalink
Use the more appropriate ResizeObserver instead of MutationObserver
Browse files Browse the repository at this point in the history
  • Loading branch information
westonruter committed Aug 14, 2024
1 parent cb5bbf6 commit 7a4d64a
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions plugins/optimization-detective/detect.js
Original file line number Diff line number Diff line change
Expand Up @@ -216,11 +216,11 @@ export default async function detect( {
);

/**
* Monitors embed for mutations.
* Monitors embed wrapper for resizes.
*
* @param {HTMLDivElement} embedWrapper Embed wrapper DIV.
*/
function monitorEmbedForMutations( embedWrapper ) {
function monitorEmbedWrapperForResizes( embedWrapper ) {
// If the embed lacks any scripting, then short-circuit since it can't possibly be doing any mutations.
if ( ! embedWrapper.querySelector( 'script, [onload]' ) ) {
return;
Expand All @@ -230,22 +230,27 @@ export default async function detect( {
}
const xpath = embedWrapper.dataset.odXpath;
let timeoutId = 0;
const observer = new MutationObserver( () => {
const observer = new ResizeObserver( ( entries ) => {
const [ entry ] = entries;
if ( timeoutId > 0 ) {
clearTimeout( timeoutId );
}
log(
`[Embed Optimizer] Pending embed height of ${ entry.contentRect.height }px for ${ xpath }`
);
// 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.
timeoutId = setTimeout( () => {
const rect = embedWrapper.getBoundingClientRect();
log(
`[Embed Optimizer] Embed height of ${ rect.height }px for ${ xpath }`
`[Embed Optimizer] Final embed height of ${ entry.contentRect.height }px for ${ xpath }`
);
observer.disconnect();
// TODO: Now amend URL metrics with this rect.height.
}, EMBED_LOAD_WAIT_MS );
} );
observer.observe( embedWrapper, { childList: true, subtree: true } );
observer.observe( embedWrapper, { box: 'content-box' } );
}
for ( const embedWrapper of embedWrappers ) {
monitorEmbedForMutations( embedWrapper );
monitorEmbedWrapperForResizes( embedWrapper );
}

// Wait until the resources on the page have fully loaded.
Expand Down

0 comments on commit 7a4d64a

Please sign in to comment.