Skip to content

Commit

Permalink
Improve performance during resize
Browse files Browse the repository at this point in the history
  • Loading branch information
johannesodland committed Feb 12, 2024
1 parent 1c71677 commit be07f1f
Showing 1 changed file with 15 additions and 13 deletions.
28 changes: 15 additions & 13 deletions src/scroll-timeline-base.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,18 @@ export function measureSubject(source, subject) {
* Update measurements of source, and update timelines
* @param {HTMLElement} source
*/
function updateMeasurements(source) {
function updateMeasurements(source, throttle) {
let details = sourceDetails.get(source);
if (details.updateScheduled && throttle) {
// Update already scheduled for the next animation frame
return;
}

details.updateScheduled = true
requestAnimationFrame(() => {
details.updateScheduled = false
})

details.sourceMeasurements = measureSource(source);

// Update measurements of the subject of connected view timelines
Expand All @@ -226,9 +236,6 @@ function updateMeasurements(source) {
}
}

if (details.updateScheduled)
return;

setTimeout(() => {
// Schedule a task to update timelines after all measurements are completed
for (const ref of details.timelineRefs) {
Expand All @@ -237,10 +244,7 @@ function updateMeasurements(source) {
updateInternal(timeline);
}
}

details.updateScheduled = false;
});
details.updateScheduled = true;
}

function updateSource(timeline, source) {
Expand Down Expand Up @@ -283,9 +287,7 @@ function updateSource(timeline, source) {

// Use resize observer to detect changes to source size
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
updateMeasurements(timelineDetails.source)
}
updateMeasurements(timelineDetails.source, true)
});
resizeObserver.observe(source);
for (const child of source.children) {
Expand All @@ -295,7 +297,7 @@ function updateSource(timeline, source) {
// Use mutation observer to detect updated style attributes on source element
const mutationObserver = new MutationObserver((records) => {
for (const record of records) {
updateMeasurements(record.target);
updateMeasurements(record.target, false);
}
});
mutationObserver.observe(source, {attributes: true, attributeFilter: ['style', 'class']});
Expand Down Expand Up @@ -836,12 +838,12 @@ export class ViewTimeline extends ScrollTimeline {
}
if (details.subject) {
const resizeObserver = new ResizeObserver(() => {
updateMeasurements(details.source)
updateMeasurements(details.source, true)
})
resizeObserver.observe(details.subject)

const mutationObserver = new MutationObserver(() => {
updateMeasurements(details.source);
updateMeasurements(details.source, false);
});
mutationObserver.observe(details.subject, {attributes: true, attributeFilter: ['class', 'style']});
}
Expand Down

0 comments on commit be07f1f

Please sign in to comment.