Which of these Javascript browser features work best?

Typically, which of these methods of writing Javascript browser functions will work better?

Method 1

function MyFunction() 
{
    if (document.browserSpecificProperty)
       doSomethingWith(document.browserSpecificProperty);
    else
       doSomethingWith(document.someOtherProperty);
}

Method 2

var MyFunction;
if(document.browserSpecificProperty) {
    MyFunction = function() {
       doSomethingWith(document.browserSpecificProperty);
    };
} else {
    MyFunction = function() {
       doSomethingWith(document.someOtherProperty);
    };
}

Edit: Click up for all subtle answers. I fixed this function for a more correct syntax.

A few questions about the answers so far - while in most cases this is a rather pointless performance improvement, there are several reasons why you can spend some time analyzing the code:

  • Slow computers, mobile devices, old browsers, etc. should work.
  • Curiosity
  • Use the same general operating principle to improve other scenarios in which an IF statement evaluation will take some time.
+3
7

, . , / . , , , , JS.

, , , . , . .

+16

, -, quirk mozilla, , , function function . , mozilla, . , .

ECMAScript , var, . (, <script> ), eval).

+7

olliej, . :

var MyFunction;
if(document.browserSpecificProperty) {
    MyFunction = function() {
       doSomethingWith(document.browserSpecificProperty);
    };
} else {
    MyFunction = function() {
       doSomethingWith(document.someOtherProperty);
    };
}

, , , , MyFunction , . ( var MyFunction; window.MyFunction = function() ... .)

+3

, , if , , .

, , . if, , . , .

, , -. .

, , , , .

+2

, , , , , .

Btw, , ?:, ( ):

var addEvent =
    document.addEventListener ? function(type, listener) {
        document.addEventListener(type, listener, false);
    } :
    document.attachEvent ? function(type, listener) {
        document.attachEvent('on' + type, listener);
    } :
    throwError;
0

: , :

var MyFunction = (function() {

      var rightProperty = document.browserSpecificProperty || document.someOtherProperty;

      return function doSomethingWith() {
            // use the rightProperty variable in your function
      }
})();
0

!

, Framework, JQuery, !

If performance is your main goal, check out SlickSpeed ! This is a page that guides the various JavaScript frames!

0
source

Source: https://habr.com/ru/post/1704623/


All Articles