Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript optimizations for Internet Explorer

It is well known that the Internet Explorer Javascript Engines are way behind in terms of performance, in particular IE 8 and older, when compared to Chrome, Safari (Webkit) or Firefox (Mozilla).

When developing a web application with significant javascript functionality, IE performs much worst than the others.

Are there any practices that could help improve your javascript code so the divide between the good performers (non-IE) and the bad performer (IE) is not that wide?

like image 674
agarcian Avatar asked Jan 13 '12 04:01

agarcian


People also ask

Does Internet Explorer use JavaScript?

As with most modern browsers, Internet Explorer supports JavaScript, which is enabled by default to allow users view dynamic interactions like display ads and animations on web pages.


2 Answers

Another couple of common solutions:

Cache frequently used DOM nodes, do not recalculate them in the same function again. E.g. instead of

$(id).parentNode.something();
$(id).parentNode.somethingOther();

use

var e = $(id).parentNode;
e.something();
e.somethingOther();

Cache frequently used objects from outer scope. E.g. instead of

if (this.options.type == 'a') {
    // ...
} else if (this.options.type == 'b') {
    // ...
}

use

var type = this.options.type;
if (type == 'a') {
    // ...
} else if (type == 'b') {
    // ...
}

This will have also positive impact on code size before and after minifying.

like image 153
Victor Avatar answered Oct 24 '22 04:10

Victor


One common way to optimize performance is caching the 'max' value in for loops.

So, let's say you have to iterate through an array called sampleArray. You could optimize the below statement:

var sampleArray = [3, 10, 12, 5, 9];

for(var i = 0; i < sampleArray.length; i++){
   var currentElement = sampleArray[i];
  // so something wit element
}

by changing it to be:

for(var i = 0, max = sampleArray.length; i < max; i++){
       var currentElement = sampleArray[i];
      // so something wit element
}

This has shown to show a pretty big performance increase in all browsers. In particular, IE7 has proven to get a 190 times increase in performance using this pattern (from High Performance Javascript)

like image 45
Oved D Avatar answered Oct 24 '22 05:10

Oved D