0
votes

In a mobile website, I have some some JavaScript code that looks like this:

<script type="text/javascript">
(function() {
  // function body omitted
}());
</script>

The first time I load the page the code is executed, but if I go back to the previous page, then load this page again, it is not executed the second time. This only happens when the page is loaded on an oldish Android browser, with User-Agent header:

Mozilla/5.0 (Linux; U; Android 2.2.1; en-gb; GT-S5570 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

On a newer Android phone, with User-Agent header:

Mozilla/5.0 (Linux; Android 4.2.1; Galaxy Nexus Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19

the code is executed each time the page is loaded. Is this a known issue with this older browser? As an aside, what exactly is the difference between

(function() {
  // function body omitted
}());

and

function() {
  // function body omitted
}();
1
you shouldnt put 2 diff questions in 1 thread, and your 2nd question is about closures, you should google it before asking..EricG
To the aside note: the second example is a function declaration and the parenthesis should lead to a syntax error, the first is an immediately invoked function expressionMoritz Roessler

1 Answers

1
votes

To answer at least the second question, because i keep seeing people using Function expressions like this

(function () {...}())

There are 2 (3) types of functions:

  • function declarations
  • function expressions
  • function statements

Function declarations can't be invoked directly. But the function as result of an expression can be invoked.

An immediately invoked function expression syntactically correct would look like

(function() {
  // function body omitted
})();

In this case the function is made an expression by enclosing it in parenthesis and then being invoked. However

(function() {
  // function body omitted
}());

works too, because of the grouping operator ( being put around the function, which automatically makes it a function expression (which is invokable) therefore you can invoke the function by putting a () directly after the functions body

But this seems to be misleading people, that structures like

function() {
  // function body omitted
}();

Are valid too, which is not the case because of the missing grouping operator not telling the interpreter its an expression. Therefore it keeps being a function declaration, which can not be invoked directly.

Here is an nice Article which explains these 3 types pretty nice