单个重绘/回流中的多个DOM更新? [英] Multiple DOM updates in a single redraw/reflow?

查看:106
本文介绍了单个重绘/回流中的多个DOM更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,填充了一个连接的用户的列表。列表本身并不经常变化,但是每一行的其中一个事情是每秒更新一个定时器(hh:mm:ss)。要更新计时器,我正在这样做:

  var curTime = new Date()。getTime()/ 1000 ; 
$('。timerCell')。each(function(){
var $ this = $(this);
var initialTime = $ this.data('sessionStartTimestamp'); //根据ajax请求中接收到的数据动态创建单元格.data。
$ this.text(unixToHumanTime(curTime - initialTime));
});

我遇到的问题是:每次更新单个计时单元时,触发重画。
有没有办法告诉浏览器等待重绘?或者可能将这些更新分组到一个更新中。
我还想到每次发生更新时都会重新渲染整个tbody,但认为这可能会比仅更新单元更加系统化。

解决方案

不要为此使用jQuery。让我们手动创建一个文档片段并将其附加到DOM中,这样我们就不会重新绘制。

  var curTime = new Date()。getTime()/ 1000; 
$('。timerCell')。text(function(){
var elm = $(this).get(0);
var frag = document.createDocumentFragment();

elem.removeChild(elem.childNodes [0]);
frag.appendChild(document.createTextNode(unixToHumanTime(curTime - initialTime)));
elem.appendChild(frag);
});


I have a table that gets populated with a list of connected users. The list itself doesn't change very often, but one of the things on each row is a timer(hh:mm:ss) that updates each second. To update the timers, I'm doing something like this:

var curTime = new Date().getTime() / 1000;
$('.timerCell').each(function(){
    var $this = $(this);
    var initialTime = $this.data('sessionStartTimestamp'); // .data gets when the cell is dynamically created based on data received in an ajax request.
    $this.text(unixToHumanTime(curTime - initialTime));
});

The issue I'm having with this is: each time that a single timer cell is updated, it triggers a redraw. Is there a way to tell the browser to wait to redraw? or perhaps some way to group these updates into a single update. I had also thought of re-rendering the entire tbody each time an update happens, but thought that would probably be more system intensive than just updating the cells.

解决方案

Don't use jQuery for this. Let's manually make a document fragment and append it to the DOM so we don't cause a re-draw.

var curTime = new Date().getTime() / 1000;
$('.timerCell').text(function(){
    var elm = $(this).get(0);
    var frag = document.createDocumentFragment();

    elem.removeChild(elem.childNodes[0]);
    frag.appendChild(document.createTextNode(unixToHumanTime(curTime - initialTime)));
    elem.appendChild(frag);
});

这篇关于单个重绘/回流中的多个DOM更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆