gitmyhub

fastdom

JavaScript ★ 6.9k updated 2y ago

Eliminates layout thrashing by batching DOM measurement and mutation tasks

Tiny JavaScript library that eliminates page jank by batching all DOM reads into one group and all writes into another, so the browser only recalculates layout once per animation frame instead of repeatedly.

JavaScriptsetup: easycomplexity 2/5

FastDom is a tiny JavaScript library that solves a specific browser performance problem called layout thrashing. When JavaScript code reads visual information from the page (such as an element's width or position) and then writes changes to the page (such as setting a new width), browsers often have to recalculate the entire page layout between each read and write. If this happens many times in quick succession, the page can become slow and janky. FastDom fixes this by collecting all reads into one batch and all writes into another, then executing reads first and writes second, once per animation frame. This way the browser only needs to recalculate layout once instead of many times.

The API has two main methods: measure for scheduling reads from the page and mutate for scheduling writes. Instead of calling DOM operations directly, developers wrap them in these two methods, and FastDom arranges them in the correct order automatically. Any scheduled job can also be cancelled before it runs.

Because FastDom is a singleton, it works across an entire application including third-party libraries that also use it. All tasks from different parts of the code feed into the same global queue, so the batching benefit applies everywhere without coordination.

The library ships with optional extensions. One adds a Promise-based API so read and write operations can be chained. Another adds task grouping. A development-only strict mode addon throws errors when DOM operations happen outside the correct phase, which helps catch performance mistakes during development before they reach production. The core library is about 600 bytes when compressed, making it lightweight enough to include in nearly any project. It is MIT licensed.

Where it fits