getBoundingClientRect vs fallback version

JavaScript performance comparison

Test case created by dan

Preparation code

<style>
div{
margin:5px;
padding:6px;
width:5px;
height:3px;
border:2px;
outline:7px;
}
div > div{
margin:15px;
padding:26px;
width:25px;
height:23px;
border:22px;
outline:72px;
}
div  div{
margin:4px;
padding:2px;
width:2px;
height:2px;
border:7px;
outline:4px;
}
</style>

<div>s<div>w<div>d<div>y<div>i<div>c<div>xz<div>ds<div>d<div> 
<div>s<div>w<div>d<div>y<div>i<div>c<div>xz<div>ds<div>d<div> 

<div>asdasd</div>
<div>asdasd</div>
<div>asdasd</div>
<div>asdasd</div>

<div id="inner">sdfsdfsdfsd</div>

</div></div></div></div></div></div></div></div></div></div>
</div></div></div></div></div></div></div></div></div></div>
<script>
  function elementInViewportOLD(el) {
    var top = el.offsetTop;
    var left = el.offsetLeft;
    var width = el.offsetWidth;
    var height = el.offsetHeight;
  
    while(el.offsetParent) {
      el = el.offsetParent;
      top += el.offsetTop;
      left += el.offsetLeft;
    }
  
    return (
      top >= window.pageYOffset &&
      left >= window.pageXOffset &&
      (top + height) <= (window.pageYOffset + window.innerHeight) &&
      (left + width) <= (window.pageXOffset + window.innerWidth)
    );
  }
  
  
  
      function elementInViewportNEW(el) {
          var rect = el.getBoundingClientRect()
    	
       	return (
            	rect.top >= 0 &&
          	rect.left >= 0 &&
          	rect.bottom <= window.innerHeight &&
          	rect.right <= window.innerWidth 
          	)
      }
  
  el = document.getElementById('inner')
</script>
    

Preparation code output

<style> div{ margin:5px; padding:6px; width:5px; height:3px; border:2px; outline:7px; } div > div{ margin:15px; padding:26px; width:25px; height:23px; border:22px; outline:72px; } div div{ margin:4px; padding:2px; width:2px; height:2px; border:7px; outline:4px; } </style> <div>s<div>w<div>d<div>y<div>i<div>c<div>xz<div>ds<div>d<div> <div>s<div>w<div>d<div>y<div>i<div>c<div>xz<div>ds<div>d<div> <div>asdasd</div> <div>asdasd</div> <div>asdasd</div> <div>asdasd</div> <div id="inner">sdfsdfsdfsd</div> </div></div></div></div></div></div></div></div></div></div> </div></div></div></div></div></div></div></div></div></div>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
old
elementInViewportOLD(el)
pending…
new
elementInViewportNEW(el)
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments

s
w
d
y
i
c
xz
ds
d
s
w
d
y
i
c
xz
ds
d
asdasd
asdasd
asdasd
asdasd
sdfsdfsdfsd