0

我使用 Dart(编译为 JS)计算页面中元素的位置。但是我读到这可能会触发回流,这会导致时间成本高昂吗?真的吗?

大型应用程序的回流/布局性能

Position offset(Element elem) {
  final docElem = document.documentElement;
  final box = elem.getBoundingClientRect();

  double left = box.left + window.pageXOffset - docElem.clientLeft;
  double top = box.top  + window.pageYOffset - docElem.clientTop;
  int width = box.width.truncate();
  int height = box.height.truncate();
  return new Position(left.truncate(), top.truncate(),
                      width, height);
}
4

1 回答 1

1

减少回流的关键是批量读写。如果在读取之前发生了挂起的写入,则读取可能会触发回流,但顺序读取不会触发回流。单独来看,很难判断这是否会触发回流。您可以通过首先使用requestAnimationFrame. 当您有多个读取并希望在所有读取之前仅触发一次回流时,这会有所帮助,但它们都必须使用requestAnimationFrame.

在 Dart 中,我们为您提供了一个animationFrame返回 a 的属性,Future使其更加符合规范。

棘手的部分是因为animationFrameandrequrestAnimationFrame是异步的,所以你的offset函数必须是 to 并返回 a Future<Position>。这必然会导致所有调用者也都是异步的。

Future<Position> offset(Element elem) {
  return window.animationFrame.then((_) {
    final docElem = document.documentElement;
    final box = elem.getBoundingClientRect();

    double left = box.left + window.pageXOffset - docElem.clientLeft;
    double top = box.top  + window.pageYOffset - docElem.clientTop;
    int width = box.width.truncate();
    int height = box.height.truncate();

    return new Position(left.truncate(), top.truncate(),
                        width, height);
  });
}
于 2014-04-05T22:19:22.400 回答