javascriptperformancedomoffsetwidth

Test DOM Element offsetHeight & offsetWidth efficiently, without attaching


I have the need to test the offsetWidth and offsetHeight of an element. Presently, the element is attached and then the offsetWidth and Height are tested, after which the element is remove.

It looks like this:

var sizer = document.createElement('DIV');
sizer.innerHTML = element; //element is a string
document.body.appendChild(sizer);
if (sizer.offsetWidth > maxWidth) {
    sizer.style.width = maxWidth);
}
document.body.removeChild(sizer);

But that is VERY SLOW!

EDIT: Complete code:

InfoBubble.prototype.getElementSize_ = function (element, opt_maxWidth, opt_maxHeight) {
var sizer = document.createElement('DIV');
sizer.style.display = 'inline';
sizer.style.position = 'absolute';
sizer.style.visibility = 'hidden';

 if (typeof element == 'string') {
    sizer.innerHTML = element;
 } else {
    sizer.appendChild(element.cloneNode(true));
 }

 document.body.appendChild(sizer);

 // If the width is bigger than the max width then set the width and size again
 if (opt_maxWidth && sizer.offsetWidth > opt_maxWidth) {
    sizer.style.width = this.px(opt_maxWidth);
    //size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight);
 }

 // If the height is bigger than the max height then set the height and size
 // again
 if (opt_maxHeight && sizer.offsetHeight > opt_maxHeight) {
     sizer.style.height = this.px(opt_maxHeight);
     //size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight);
 }
 var size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight);

 document.body.removeChild(sizer);
 return size;
};

Solution

  • The whole page may be being redrawn- Put the thing in an absolutly positioned, visibility hidden div element, it should be faster.