在后台构建一个dom子树

时间:2018-06-14 23:16:02

标签: javascript dom worker

在javascript中构建一个大而复杂的dom子树是非常缓慢和昂贵的。是否可以在后台构建这样的树,可能使用worker并且只在建筑物完工时将其附加到主dom树?

我知道工作者无法访问dom和xml库,但是在需要时可能会有一个常见的延迟加载子树的解决方法。

var c = document.createDocumentFragment();

// takes several seconds to execute, should not block main thread.
// may be inside a worker...
buildLargeAndComplexSubtree(c);

// append subtree to the main tree in the main thread.
document.body.appendChild(c);

1 个答案:

答案 0 :(得分:0)

使用setTimeout可能有助于将其从主线程中删除并提高性能:

setTimeout(function () {
    var c = document.createDocumentFragment();
    // takes several seconds to execute, should not block main thread.
    // may be inside a worker...
    buildLargeAndComplexSubtree(c);
    // append subtree to the main tree in the main thread.
    document.body.appendChild(c);
}, 0);