perf(stickyHeader): ️ only recalc stickyHeader height when width changes

This commit is contained in:
alistair3149 2024-11-08 21:24:56 -05:00
parent 252e98b085
commit d4d6345050
No known key found for this signature in database
2 changed files with 18 additions and 8 deletions

View file

@ -10,18 +10,18 @@ function initResizeObserver( onResize, onResizeStart, onResizeEnd ) {
let resizeStarted = false;
/* eslint-disable-next-line compat/compat */
return new ResizeObserver( () => {
return new ResizeObserver( ( entries ) => {
if ( onResizeStart && !resizeStarted ) {
onResizeStart();
onResizeStart( entries[ 0 ] );
resizeStarted = true;
}
onResize();
onResize( entries[ 0 ] );
if ( onResizeEnd ) {
clearTimeout( window.resizedFinished );
window.resizedFinished = setTimeout( () => {
onResizeEnd();
onResizeEnd( entries[ 0 ] );
resizeStarted = false;
}, 250 );
}

View file

@ -251,23 +251,33 @@ const main = () => {
pageHeaderObserver.observe( stickyIntersection );
// Initialize var
let bodyWidth = 0;
const bodyObserver = resizeObserver.initResizeObserver(
// onResize
() => {},
// onResizeStart
() => {
( entry ) => {
// eslint-disable-next-line es-x/no-optional-chaining
bodyWidth = entry.borderBoxSize?.[ 0 ].inlineSize;
// Disable all CSS animation during resize
if ( document.documentElement.classList.contains( 'citizen-animations-ready' ) ) {
document.documentElement.classList.remove( 'citizen-animations-ready' );
}
pauseStickyHeader();
},
// onResizeEnd
() => {
( entry ) => {
// eslint-disable-next-line es-x/no-optional-chaining
const newBodyWidth = entry.borderBoxSize?.[ 0 ].inlineSize;
const shouldRecalcStickyHeader =
document.body.classList.contains( PAGE_TITLE_INTERSECTION_CLASS ) &&
typeof newBodyWidth === 'number' &&
bodyWidth !== newBodyWidth;
// Enable CSS animation after resize is finished
document.documentElement.classList.add( 'citizen-animations-ready' );
// Recalculate sticky header height at the end of the resize
if ( document.body.classList.contains( PAGE_TITLE_INTERSECTION_CLASS ) ) {
if ( shouldRecalcStickyHeader ) {
resumeStickyHeader();
}
}