Skip to content

Instantly share code, notes, and snippets.

@NoamELB
Last active March 29, 2019 14:55
Show Gist options
  • Save NoamELB/102a3eb9ab8e3f5b61eb7d04d4913f5e to your computer and use it in GitHub Desktop.
Save NoamELB/102a3eb9ab8e3f5b61eb7d04d4913f5e to your computer and use it in GitHub Desktop.
update height with request animation frame
updateHeight(isOpen) {
this.lastRAF && cancelAnimationFrame(this.lastRAF);
if (isOpen) {
this.lastRAF = requestAnimationFrame(() => {
// read:
const height =`${this.contentEl.scrollHeight}px`;
this.lastRAF = requestAnimationFrame(() => {
// write in a different frame:
this.containerEl.style.height = height;
this.lastRAF = null;
});
});
} else {
this.containerEl.style.height = '0px';
}
}
@copycut
Copy link

copycut commented Nov 28, 2017

Why do you nest two requestAnimationFrame ? line 7 & 8.

@cotyembry
Copy link

I bet its to reduce the risk of having the browser to do a recalculate style or recompute style to avoid layout thrashing? Just a guess. See how he reads the DOM in one frame and writes to the DOM in another? Rather than reading and writing in the same frame, but I still dont know if this acutally helps, just my guess @copycut

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment