Git Product home page Git Product logo

fastdom's Introduction

fastdom Twitter Follow

Build Status NPM version npm Coverage Status gzip size

Eliminates layout thrashing by batching DOM read/write operations (~600 bytes minified gzipped).

fastdom.measure(() => {
  console.log('measure');
});

fastdom.mutate(() => {
  console.log('mutate');
});

fastdom.measure(() => {
  console.log('measure');
});

fastdom.mutate(() => {
  console.log('mutate');
});

Outputs:

measure
measure
mutate
mutate

Examples

Installation

FastDom is CommonJS and AMD compatible, you can install it in one of the following ways:

$ npm install fastdom --save

or download.

How it works

FastDom works as a regulatory layer between your app/library and the DOM. By batching DOM access we avoid unnecessary document reflows and dramatically speed up layout performance.

Each measure/mutate job is added to a corresponding measure/mutate queue. The queues are emptied (reads, then writes) at the turn of the next frame using window.requestAnimationFrame.

FastDom aims to behave like a singleton across all modules in your app. When any module requires 'fastdom' they get the same instance back, meaning FastDom can harmonize DOM access app-wide.

Potentially a third-party library could depend on FastDom, and better integrate within an app that itself uses it.

API

FastDom#measure(callback[, context])

Schedules a job for the 'measure' queue. Returns a unique ID that can be used to clear the scheduled job.

fastdom.measure(() => {
  const width = element.clientWidth;
});

FastDom#mutate(callback[, context])

Schedules a job for the 'mutate' queue. Returns a unique ID that can be used to clear the scheduled job.

fastdom.mutate(() => {
  element.style.width = width + 'px';
});

FastDom#clear(id)

Clears any scheduled job.

const read = fastdom.measure(() => {});
const write = fastdom.mutate(() => {});

fastdom.clear(read);
fastdom.clear(write);

Strict mode

It's very important that all DOM mutations or measurements go through fastdom to ensure good performance; to help you with this we wrote fastdom-strict. When fastdom-strict.js is loaded, it will throw errors when sensitive DOM APIs are called at the wrong time.

This is useful when working with a large team who might not all be aware of fastdom or its benefits. It can also prove useful for catching 'un-fastdom-ed' code when migrating an app to fastdom.

<script src="fastdom.js"></script>
<script src="fastdom-strict.js"></script>
element.clientWidth; // throws
fastdom.mutate(function() { element.clientWidth; }); // throws
fastdom.measure(function() { element.clientWidth; }); // does not throw
"Error: Can only get .clientWidth during 'measure' phase"
  • fastdom-strict will not throw if nodes are not attached to the document.
  • You should use fastdom-strict in development to catch rendering performance issues before they hit production.
  • It is not advisable to use fastdom-strict in production.

Exceptions

FastDom is async, this can therefore mean that when a job comes around to being executed, the node you were working with may no longer be there. These errors are usually not critical, but they can cripple your app.

FastDom allows you to register a catch handler. If fastdom.catch has been registered, FastDom will catch any errors that occur in your jobs, and run the handler instead.

fastdom.catch = (error) => {
  // Do something if you want
};

Extensions

The core fastdom library is designed to be as light as possible. Additional functionality can be bolted on in the form of 'extensions'. It's worth noting that fastdom is a 'singleton' by design, so all tasks (even those scheduled by extensions) will reach the same global task queue.

Fastdom ships with some extensions:

Using an extension

Use the .extend() method to extend the current fastdom to create a new object.

<script src="fastdom.js"></script>
<script src="extensions/fastdom-promised.js"></script>
// extend fastdom
const myFastdom = fastdom.extend(fastdomPromised);

// use new api
myFastdom.mutate(...).then(...);

Extensions can be chained to construct a fully customised fastdom.

const myFastdom = fastdom
  .extend(fastdomPromised)
  .extend(fastdomSandbox);

Writing an extension

const myFastdom = fastdom.extend({
  measure(fn, ctx) {
    // do custom stuff ...

    // then call the parent method
    return this.fastdom.measure(fn, ctx);
  },

  mutate: ...
});

You'll notice this.fastdom references the parent fastdom. If you're extending a core API and aren't calling the parent method, you're doing something wrong.

When distributing an extension only export a plain object to allow users to compose their own fastdom.

module.exports = {
  measure: ...,
  mutate: ...,
  clear: ...
};

Tests

$ npm install
$ npm test

Author

Contributors

License

(The MIT License)

Copyright (c) 2016 Wilson Page [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

fastdom's People

Contributors

alexandertrefz avatar amilajack avatar betabong avatar cvetanov avatar daniel-nagy avatar dhenson02 avatar elving avatar fgoll avatar georgecrawford avatar hypnosphi avatar hywan avatar kasperisager avatar keslert avatar kkirsche avatar krinkle avatar martijnwelker avatar melatonin64 avatar oliverjash avatar pawelzwronek avatar rburgt avatar rich-harris avatar rowanbeentje avatar rs3d avatar th507 avatar tusharmath avatar wilsonpage avatar

Watchers

 avatar

fastdom's Issues

fastdom源码学习(三)

全部代码

fastdom的使用

在真正看源码之前, 首先通过其fastdom的api使用以及对于会导致布局抖动的原因, 我们将自己尝试着去解决这个问题, fastdom的使用很简单, 就两个方法: measure(读相关), mutate(写相关)

fastdom.measure(function() {
	var top = ball.offsetTop;
	fastdom.mutate(function() {
            ball.style.left = ((Math.sin(ball.offsetTop + timestamp/1000) + 1) * 500) + 'px'
	});
});

fastdom的实现

对于其使用, 我们可以大致知道measure将是记录读取相关的操作, mutate是记录写相关的操作, 所以:

var FastDom = function() {
  this.reads = [] // 记录读操作的队列
  this.writes = [] // 记录写操作的队列
}

Fastdom.prototype = {
  measure: function(func) {
    this.reads.push(func) // 读操作入队
  },
  mutate: function(func) {
    this.writes.push(func) // 写操作入队
  },
}

好了, 我们将操作入队之后呢, 我们可以看到fastdom的api, 调用完measure, mutate 之后就不需要再另外调用其他api 就可以开始执行任务了, 那所以measure/mutate肯定就会开始触发任务队列的执行.

var FastDom = function() {
  this.reads = [] // 记录读操作的队列
  this.writes = [] // 记录写操作的队列
}

Fastdom.prototype = {
  measure: function(func) {
    this.reads.push(func) // 读操作入队
    this.schedule() // 调度
  },
  mutate: function(func) {
    this.writes.push(func) // 写操作入队
    this.schedule() // 调度
  },
  schedule() {  }
}

那么如何调度呢, 在解决怎么调度之前, 我们任务队列有了, 那怎么执行这个任务队列呢?

Fastdom.prototype = {
  ...,
  runTasks: function(tasks) {
    var task; while (task = tasks.shift()) task();
  },
}

上面这个方法应该就不用多说了吧, 那接下来就是对于我们的读写分离, 怎么分离呢, 就是先执行完读队列中的内容, 再执行写队列中的内容:

Fastdom.prototype = {
  ...,
    flushTasks() {
      this.runTasks(this.reads)
      this.runTasks(this.writes)
  },

}

那么接下来就是调度的问题了, 我们知道, 对于每个measure, mutate我们都触发了调度, 那么对于批量的读写, 我们首先需要确保的就是只执行一次调度操作, 当全部读写操作执行完, 我们再进行下一轮, 所以这边我们在调度中首先需要的就是引入锁, 还有我们每一次调度其中就是执行完所有的读写操作, 那么我们可以直接就调用flushTasks吗

Fastdom.prototype = {
    flushTasks() {
      this.runTasks(this.reads)
      this.runTasks(this.writes)
      this.lock = false // 解锁
  },
  schedule() { 
      if (this.lock) return
      this.lock = true // 锁上
      this.flushTasks() // 执行读写操作,  <<<思考>>>
  }
}

好了, 大家觉得上述代码有问题吗(那不是废话吗, 我都没说结束了), 好的, 我们知道, 我们需要做的是, 收集批量(重点)的读写, 但是我们上面的代码中, 我们可以想我们for循环400次, 执行了400次的measure, measure又触发了schedule, 而schedule马上执行flushTasks, 我们知道前端是单线程, 所以如上代码其实就是在同步执行, 每次只收集到一次读/写操作, 就触发flushTasks了, 所以我们希望的是收集较多的reads, 再去执行flushTasks, 而我们又是在做dom的更新, 因此将flushTasks的执行放到requestAnimationFrame就在合适不过了, so:

Fastdom.prototype = {
    flushTasks() {
      this.runTasks(this.reads)
      this.runTasks(this.writes)
      this.lock = false // 解锁
  },
  schedule() { 
      if (this.lock) return
      this.lock = true // 锁上
      window.requestAnimationFrame(this.flushTasks.bind(this)) // RAF
  }
}

这时候再使用我们实现的fastdom, 这时候我们可以发现performance:
image
没有了大量的强制布局, 一帧时间也降到了 30ms, 好了, 经此, 大家再去看fastdom的源码, 应该没什么问题了, 感谢各位老板

fastdom源码学习(一)

为什么要用到fastdom

首先让我们先了解一下以下内容

浏览器的渲染流程:

JavaScript             -> Style              -> Layout        -> Paint -> Composite
(主要用来触发视觉变换)    (对样式重新计算)     (布局, 大小/位置)     (绘制)     (复合, 不是所有东西都画在一个图层上, 类似ps)

理论上这五个步骤都是必须经历的, 但有些样式不会影响 Layout/Paint, 所有浏览器进行了优化, 这些样式可以不经历 Layout/Paint

影响回流(布局)的操作

  • 添加删除元素
  • 操作styles
  • display: none
  • offsetLeft, scrollTop, clientWidth
  • 移动元素位置
  • 修改浏览器大小, 字体大小

避免layout thrashing(布局抖动)

当出现如下代码:

const update = () => {
  dom.style.width = dom.offsetTop + Math.random() * 500 + 'px' 
  window.requestAnimationFrame(update)
}

浏览器为了尽量的提高布局性能, 会尽量的去把对修改布局属性的一些操作推迟, 但当你为了去获取一些获得布局相关的属性, 比如offsetTop, 浏览器不得不立即去计算获取最新的值, 所以在这边赋值前会强制的去计算, 会产生连续的强制回流, 出现卡顿

解决:

  • 避免回流: transform, translate, 只会触发复合的过程
  • 读写分离: fastdom

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.