Last active
March 28, 2018 12:29
-
-
Save dmail/05e37928eeaf88ebfd60b9142a83a6e0 to your computer and use it in GitHub Desktop.
Utility to ensure UI mutations are executed together
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const batchUIMutation = (fnMutatingUI) => { | |
if (typeof window !== 'undefined' && window.requestAnimationFrame) { | |
const id = requestAnimationFrame(() => { | |
cancelAnimationFrame(id) | |
fnMutatingUI() | |
}) | |
return () => cancelAnimationFrame(id) | |
} | |
const id = setTimeout(() => { | |
clearTimeout(id) | |
fnMutatingUI() | |
}, 17) | |
return () => clearTimeout(id) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { batchUIMutation } from "./batch-ui-mutations.js" | |
// in browsers supporting requestAnimationFrame mutations on body.style below | |
// will be batched by browser to trigger only one repaint/reflow | |
// inside other browsers, they will be grouped thanks to setTimeout without benefits of requestAnimationFrame | |
batchUIMutation(() => { | |
document.body.style.color = "red" | |
}) | |
batchUIMutation(() => { | |
document.body.style.paddingTop = "10px" | |
}) | |
// please note each call to batchUIMutation can be cancelled as shown below | |
const cancel = batchUIMutation(() => { | |
document.body.style.paddingLeft = "10px" | |
}) | |
cancel() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment