macrael
macrael

Reputation: 346

Why is this javascript function so slow on Firefox?

This function was adapted from the website: 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;
}

I am running this function as part of another function on window.resize, and it is causing performance problems on Firefox 3.6 that do not exist on current Safari or Chrome. Firefox's profiler says I'm spending the most time in this function and I'm curious as to why that is.

Is there a way to get the em size in javascript without doing all this work? I would like to recalculate the size on resize incase the user has changed it.

Upvotes: 4

Views: 5953

Answers (2)

David Baron
David Baron

Reputation: 920

Seems like the function could just be

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

In other words, you can just get the computed font size of the element rather than creating a div and sizing it.

Upvotes: 14

Michael Lorton
Michael Lorton

Reputation: 44376

Try this (it's the same function with the value stashed so it only runs once):

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);
    };
};

Upvotes: 2

Related Questions