最近,我收到了这样的警告,这是我第一次收到:
JavaScript任务长时间运行,耗时234ms
执行JavaScript时强制回流花了45毫秒
我正在做一个小组项目,我不知道这是从哪里来的。这在以前从未发生过。突然,当其他人参与到这个项目中时,它出现了。如何查找导致此警告的文件/函数?我一直在寻找答案,但主要是关于如何解决它的解决方案。如果我连问题的根源都找不到,我就解决不了。
在这种情况下,警告只出现在Chrome上。我尝试使用Edge,但没有收到任何类似的警告,而且我还没有在Firefox上测试它。
我甚至从jquery.min.js中得到错误:
[违规]Handler占用了231ms的运行时(允许50ms
这是谷歌Chrome浏览器的违规错误,显示详细日志级别启用时。
错误信息示例:
解释:
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.
原文:最小化浏览器回流,作者:Lindsey Simon, UX开发人员,发表于developers.google.com。
这是链接谷歌Chrome给你在性能分析器,在布局配置文件(淡紫色区域),对警告的更多信息。
在Chrome控制台中Network选项卡下查找加载时间最长的脚本。
在我的例子中,有一组Angular add on脚本,我已经包含了,但还没有在应用中使用:
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-utils/0.1.1/angular-ui-utils.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-animate.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-aria.min.js"></script>
只有这些JavaScript文件的加载时间比“长时间运行任务”错误指定的时间长。
所有这些文件都在我的其他网站上运行,没有产生错误,但我在一个几乎没有任何功能的新web应用程序上得到了这个“长时间运行任务”错误。删除后错误立即停止。
我最好的猜测是,这些Angular add on正在递归地寻找DOM中越来越深的部分来寻找它们的开始标签——没有找到,它们必须在退出之前遍历整个DOM,这比Chrome预期的时间要长——因此出现了警告。
我在我的代码中找到了这条消息的根,它搜索并隐藏或显示节点(脱机)。这是我的代码:
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个节点)。