【问题标题】:Why is this javascript function so slow on Firefox?为什么这个 javascript 函数在 Firefox 上这么慢?
【发布时间】:2011-06-02 02:10:54
【问题描述】:

此功能改编自网站:http://eriwen.com/javascript/measure-ems-for-layout/

function getEmSize(el) {
    var tempDiv = document.createElement("div");
    tempDiv.style.height = "1em";
    el.appendChild(tempDiv);
    var emSize = tempDiv.offsetHeight;
    el.removeChild(tempDiv);
    return emSize;
}

我将这个函数作为 window.resize 上另一个函数的一部分运行,它在 Firefox 3.6 上导致了当前 Safari 或 Chrome 上不存在的性能问题。 Firefox 的分析器说我在这个函数上花费的时间最多,我很好奇为什么会这样。

有没有办法在不做所有这些工作的情况下在 javascript 中获取 em 大小?我想重新计算 resize 的大小,以防用户更改它。

【问题讨论】:

  • 你能告诉我们这个函数是如何在window.resize的其他函数中使用的吗?
  • @thephpdeveloper 我可以,但我认为这是多余的。该函数只在该函数中调用一次,结果被缓存。
  • Firefox 有分析器吗?它是内置的还是您在谈论 JavaScript 调试器 (Venkman)?
  • @MatrixFrog 抱歉,FF 没有内置。 Firebug 有一些分析功能。

标签: javascript performance firefox


【解决方案1】:

似乎功能可能只是

function getEmSize(el) {
    return Number(getComputedStyle(el, "").fontSize.match(/(\d+)px/)[1]);
}

换句话说,您可以只获取元素的计算字体大小,而不是创建一个 div 并调整它的大小。

【讨论】:

  • 感谢您的回答,大卫。我在 2008 年编写了原始函数,当时我们还必须支持 Safari 2(它没有 getComputedStyle())。我怀疑最好的答案实际上是您对缓存想法的回答。我已经相应地更新了我的博客文章。
  • 我喜欢这个。我遇到的唯一奇怪的错误是在 Chrome 上。因为我在调整大小时调用了这个函数,所以 Chrome 会在控制台中记录一些错误,使它看起来像是在同时运行该函数的两个副本,而一些数据被遗漏了。
  • 顺便说一下,得到的像素值可能是一个浮点数,所以正则表达式应该类似于/(\d+(\.\d*)?)px/
  • parseFloat(getComputedStyle(el, "").fontSize);
【解决方案2】:

试试这个(它与隐藏值的函数相同,因此它只运行一次):

var getEmSize =  function() {
    var underlyingFunction = function(el) {
      var tempDiv = document.createElement("div");
      tempDiv.style.height = "1em";
      el.appendChild(tempDiv);
      var emSize = tempDiv.offsetHeight;
      el.removeChild(tempDiv);
      underlyingFunction = function() {
        return emSize;
      };
      return emSize;
    };
    return function(el) {
       return underlyingFunction(el);
    };
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-17
    • 2011-10-10
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 2022-12-04
    • 2013-02-26
    相关资源
    最近更新 更多