S Jung
S Jung

Reputation: 160

Is there a performance difference in using $(window).width() and window.innerWidth?

If I'm already using jQuery in my app, but want to improve performance as much as I can. Does it improve performance any to use vanilla JS instead of jQuery (for example) for getting window width in some places of my code?

Upvotes: 1

Views: 1113

Answers (2)

Zzz
Zzz

Reputation: 3025

There is always a performance price for using JQuery instead of plain (vanilla) JavaScript, since it is a library built on top of JavaScript to address browser native DOM API inconsistencies and make iteration over elements simpler (to name a few things).

Some examples of when to use JQuery:

  • Tedious cross browser situations (for example AJAX)
  • To facilitate chaining, simplify working on groups of elements together.

An exapmle of when not to use JQuery:

When executing a loop many times.

Unwrap all tags of a certain type. JQuery is simple but doesn't perform well when there are MANY elements to iterate over:

$('span').unwrap();  // unwrap all span elements

The native DOM API will perform better:

var spans = document.getElementsByTagName('span');

while( spans[0] ) {
    var parent = spans[0].parentNode;
    while( spans[0].firstChild ) {
        parent.insertBefore( spans[0].firstChild, spans[0]);
    }
    parent.removeChild( spans[0] );
}
  • window.innerWidth: with scrollbar
  • $(window).innerWidth(): wrong usage
  • $(window).width(): without scrollbar
  • mediaquery: with scrollbar (at least the standard ones)

$(window).innerWidth(): this is actually a wrong way to get the inner width of window, because api.jquery.com/innerWidth states that “This method is not applicable to window and document objects; for these, use .width() instead.”

But what if we just need the inner width of window? We might need to adjust images according to width. In this case, use window.innerWidth.

window.innerWidth: quite literally, the width of window WITH scroll bar (as all mediaquery should behave). But sadly, IE8 doesn’t support it.

So use:

var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

To be clear, window.innerWidth is different from the latter two since only window.innerWidth includes scrollbar. But we don’t need to worry about getting the wrong width in IE8 because it doesn’t support Mediaquery–if it wants the width, it’ll have to resort to javascript solutions anyway.

Source: http://luxiyalu.com/window-innerwidth-vs-window-innerwidth/

Upvotes: 0

Phillip
Phillip

Reputation: 6253

There is actually a huge performance difference! I tried it out in jsPerf: https://jsperf.com/window-width-jquery-vs-vanilla/1

Vanilla trumps jQuery!

There is of course notable overhead when you have to instantiate a new jQuery object ($(window)). If you must use jQuery, save the window jQuery object to a variable.

Upvotes: 2

Related Questions