1

In an existing application, I just felt on the following code:

function _repaint(elem) {
    elem.style.display = 'none';
    elem.offsetHeight; // jshint ignore:line
    elem.style.display = '';
}

The second line seems completly useless to me, and I don't notice any changes to the app when removing it. Yet, it is voluntarily ignored for jshint. So, I wonder what is its purpose?

Won't the JavaScript engine remove this useless line for optimization?

Jonathan Petitcolas
  • 4,254
  • 4
  • 31
  • 42
  • 1
    Since it's a DOM property, there might be some magic that happens when it's accessed. Like it forces the rendering engine to recalculate the layout due to the changed CSS on the previous line. – Barmar Sep 11 '15 at 09:06
  • If this code is in git (or other source version system) you need to hunt down the person responsible to figure out the answer :) – Ankur Sep 11 '15 at 09:08
  • 3
    http://stackoverflow.com/a/3485654/2182767 - trick! :) But it is question from 2010, I don't know if it works here in 2015 – Andrey Sep 11 '15 at 09:08
  • 1
    If a property has a getter function, the function will be called when the property is accessed, even if the value isn't used. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get – Barmar Sep 11 '15 at 09:10
  • 1
    The person writing that line should be taken out back and beat severely with wet spaghetti. Why? Because **this is a context where a comment is not optional**. Unforgiveable not to have `// WebKit bug workaround: http://stackoverflow.com/questions/3485365/` on it, or similar. – T.J. Crowder Sep 11 '15 at 09:13

1 Answers1

2

The second line

elem.offsetHeight;

seems to have no effects, but in reality it has a huge one: calculating .offsetHeight of any element forces the browser to repaint/reflow the whole document. It's probably a hack for some obscure browser bug on some specific platform/device.

Edit: if you're sure the bug doesn't exists any more, or it doesn't matter because you no longer support the platform when it was needed I'd recommend to remove this line ( especially if it's called many times). It is a costly operation and should be avoided for performance reasons.

pawel
  • 35,827
  • 7
  • 56
  • 53