It depends on how many times this is executed. If you execute this multiple times inside a resize function, setting a global variable that stores your element will speed up your code since it does not have to look up the variable every time. So if you are using window.resize
, this would be a tad bit faster:
var myWebPart = document.getElementById('my-webpart');
var docElement = document.documentElement
window.addEventListener('resize', function(){
myWebPart.style.height = (docElement.clientHeight - 80) + 'px';
}, false);
However, the difference we are talking about is negligible. I always tend to look at this as document.getElementById()
being a function and functions need execution time, so if you already have the answer (the element) and you are going to use it multiple times, then it might be best to store the answer in a variable. If, however, you only use it once, it's best to not store it in a variable as you are increasing the memory usage for something that does not need to be stored, as well as executing a tiny bit of code to allow for this memory to be used. Every bit slows down, but we are really talking minimal changes here.
Update
I'm adding my two pence concerning the height issue you are mentioning. It is easier to do with CSS, but I would avoid using box-sizing
, instead using something like the below as it works as expected across browsers while having a fallback for older browsers:
/* Define a height for older browsers */
height: 80%;
/* Use calc to get the simulated border-box-sizing height / ignored by old browsers */
height: calc(100% - 80px);
/* Define a padding for older browsers */
padding-bottom: 20%;
/* Use calc to get the simulated border-box-sizing padding / ignored by old browsers */
padding-bottom: calc(80px);
I know box-sizing
is popular for this, but I think calc
solved our problem to begin with, and it makes box behaviour more predictable as they will always work in the same fashion.