最近,我收到了这样的警告,这是我第一次收到:

JavaScript任务长时间运行,耗时234ms 执行JavaScript时强制回流花了45毫秒

我正在做一个小组项目,我不知道这是从哪里来的。这在以前从未发生过。突然,当其他人参与到这个项目中时,它出现了。如何查找导致此警告的文件/函数?我一直在寻找答案,但主要是关于如何解决它的解决方案。如果我连问题的根源都找不到,我就解决不了。

在这种情况下,警告只出现在Chrome上。我尝试使用Edge,但没有收到任何类似的警告,而且我还没有在Firefox上测试它。

我甚至从jquery.min.js中得到错误:

[违规]Handler占用了231ms的运行时(允许50ms


当前回答

我在我的代码中找到了这条消息的根,它搜索并隐藏或显示节点(脱机)。这是我的代码:

search.addEventListener('keyup', function() {
    for (const node of nodes)
        if (node.innerText.toLowerCase().includes(this.value.toLowerCase()))
            node.classList.remove('hidden');
        else
            node.classList.add('hidden');
});

性能选项卡(分析器)显示事件花费了大约60毫秒:

Now:

search.addEventListener('keyup', function() {
    const nodesToHide = [];
    const nodesToShow = [];
    for (const node of nodes)
        if (node.innerText.toLowerCase().includes(this.value.toLowerCase()))
            nodesToShow.push(node);
        else
            nodesToHide.push(node);

    nodesToHide.forEach(node => node.classList.add('hidden'));
    nodesToShow.forEach(node => node.classList.remove('hidden'));
});

性能选项卡(分析器)现在显示事件大约1毫秒:

而且我觉得现在搜索速度更快了(229个节点)。

其他回答

不管怎样,这是我在遇到

[Violation] Forced reflow while executing JavaScript took <N>ms

警告。所讨论的页面是由用户内容生成的,因此我对DOM的大小实际上没有多大影响。在我的例子中,问题是一个有两列的表,可能有数百甚至数千行。(没有按需行加载实现,对不起!)

使用jQuery,在按下键时,页面选择一组行并切换它们的可见性。我注意到,在该集合上使用toggle()比显式使用hide() & show()更容易触发警告。

有关此特定性能场景的更多详细信息,请参见本文。

我在我的代码中找到了这条消息的根,它搜索并隐藏或显示节点(脱机)。这是我的代码:

search.addEventListener('keyup', function() {
    for (const node of nodes)
        if (node.innerText.toLowerCase().includes(this.value.toLowerCase()))
            node.classList.remove('hidden');
        else
            node.classList.add('hidden');
});

性能选项卡(分析器)显示事件花费了大约60毫秒:

Now:

search.addEventListener('keyup', function() {
    const nodesToHide = [];
    const nodesToShow = [];
    for (const node of nodes)
        if (node.innerText.toLowerCase().includes(this.value.toLowerCase()))
            nodesToShow.push(node);
        else
            nodesToHide.push(node);

    nodesToHide.forEach(node => node.classList.add('hidden'));
    nodesToShow.forEach(node => node.classList.remove('hidden'));
});

性能选项卡(分析器)现在显示事件大约1毫秒:

而且我觉得现在搜索速度更快了(229个节点)。

我在Apache Cordova源代码中找到了一个解决方案。 它们是这样实现的:

var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve();
var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); };

实现简单,但方法聪明。

而不是Android 4.4,使用Promise。 对于旧的浏览器,使用setTimeout()


用法:

nextTick(function() {
  // your code
});

插入这个恶作剧代码后,所有警告消息都消失了。

为了确定问题的根源,运行你的应用程序,并记录在Chrome的性能选项卡。

在那里,您可以检查运行时间较长的各种函数。在我的情况下,一个与警告相关的控制台是由AdBlock扩展加载的文件,但这可能是其他的东西在你的情况下。

检查这些文件,并尝试识别这是一些扩展的代码还是你的。(如果是你的问题,那么你已经找到了问题的根源。)

正如大家提到的,这些只是警告。然而,如果您热衷于解决这些问题(这是应该的),那么您需要首先确定导致警告的原因。没有一个原因可以导致强制回流警告。 有人列出了一些可能的选择。您可以跟随讨论了解更多信息。 以下是可能原因的要点:

What forces layout / reflow All of the below properties or methods, when requested/called in JavaScript, will trigger the browser to synchronously calculate the style and layout*. This is also called reflow or layout thrashing, and is common performance bottleneck. Element Box metrics elem.offsetLeft, elem.offsetTop, elem.offsetWidth, elem.offsetHeight, elem.offsetParent elem.clientLeft, elem.clientTop, elem.clientWidth, elem.clientHeight elem.getClientRects(), elem.getBoundingClientRect() Scroll stuff elem.scrollBy(), elem.scrollTo() elem.scrollIntoView(), elem.scrollIntoViewIfNeeded() elem.scrollWidth, elem.scrollHeight elem.scrollLeft, elem.scrollTop also, setting them Focus elem.focus() can trigger a double forced layout (source) Also… elem.computedRole, elem.computedName elem.innerText (source) getComputedStyle window.getComputedStyle() will typically force style recalc (source) window.getComputedStyle() will force layout, as well, if any of the following is true: The element is in a shadow tree There are media queries (viewport-related ones). Specifically, one of the following: (source) * min-width, min-height, max-width, max-height, width, height * aspect-ratio, min-aspect-ratio, max-aspect-ratio device-pixel-ratio, resolution, orientation The property requested is one of the following: (source) height, width * top, right, bottom, left * margin [-top, -right, -bottom, -left, or shorthand] only if the margin is fixed. * padding [-top, -right, -bottom, -left, or shorthand] only if the padding is fixed. * transform, transform-origin, perspective-origin * translate, rotate, scale * webkit-filter, backdrop-filter * motion-path, motion-offset, motion-rotation * x, y, rx, ry window window.scrollX, window.scrollY window.innerHeight, window.innerWidth window.getMatchedCSSRules() only forces style Forms inputElem.focus() inputElem.select(), textareaElem.select() (source) Mouse events mouseEvt.layerX, mouseEvt.layerY, mouseEvt.offsetX, mouseEvt.offsetY (source) document doc.scrollingElement only forces style Range range.getClientRects(), range.getBoundingClientRect() SVG Quite a lot; haven't made an exhaustive list , but Tony Gentilcore's 2011 Layout Triggering List pointed to a few. contenteditable Lots & lots of stuff, …including copying an image to clipboard (source)

点击这里查看更多信息。

另外,这里是原始问题的Chromium源代码,以及关于警告的性能API的讨论。


编辑:谷歌还有一篇关于如何在PageSpeed Insight上最小化布局回流的文章。它解释了什么是浏览器回流:

Reflow is the name of the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document. Because reflow is a user-blocking operation in the browser, it is useful for developers to understand how to improve reflow time and also to understand the effects of various document properties (DOM depth, CSS rule efficiency, different types of style changes) on reflow time. Sometimes reflowing a single element in the document may require reflowing its parent elements and also any elements which follow it.

此外,它还解释了如何将其最小化:

Reduce unnecessary DOM depth. Changes at one level in the DOM tree can cause changes at every level of the tree - all the way up to the root, and all the way down into the children of the modified node. This leads to more time being spent performing reflow. Minimize CSS rules, and remove unused CSS rules. If you make complex rendering changes such as animations, do so out of the flow. Use position-absolute or position-fixed to accomplish this. Avoid unnecessary complex CSS selectors - descendant selectors in particular - which require more CPU power to do selector matching.