Soooooooooooooooo...
I have an IF statement that nowadays will evaluate to true 99.7% of the time, which consists of a check to see if the browser is DOM 1+ capable, and then load a big block of code.
So it's logical to put an "if (true)", and omit the "else" part, but i wonder if the older browsers开发者_JAVA百科 will still continue to parse the code and allocate memory, before finally deciding to break execution....
Not that i care at this point, since we've had decent browsers for 10+ years now, but for future reference, i hope somebody knows.
I guess my question is more or less this: does the browser parse the whole file and allocate memory before executing the first conditional statement, which is the first thing before anything else?
Thanks in advance :)
There are two things that are hoisted out of execution context and will have an effect even if the code in question is never reached: function
and var
.
Putting a var
declaration in a code block will “reserve memory” for that variable as soon as the block is entered, but the value of that variable will only be a pointer to the undefined
object, so it's only a trivially small number of bytes.
Putting a function
statement in a code block will both “reserve memory” for the variable and evaluate the function
, assigning the resulting Function
object to the variable, before the first line of code in the block is executed. That's how you can call a function that's only defined further down the script.
Under ECMAScript standard rules, you may only put function
statements in the root of the code block; that is to say this:
if (true) {
function f() {
...
}
}
is illegal. However, browsers still generally allow it and exactly what happens when you do it differs between browsers. Avoid this. (Also avoid named inline function expressions, which are erroneously subject to hoisting and double-evaluation in IE's JScript.)
If you really want to stop any memory being allocated for variables and functions you don't intend to use, put them in a function block of their own. This is a common tactic anyway for maintaining clean namespaces in library code. eg.:
if (condition) (function() {
var foo= 1;
function bar() {
alert(foo);
}
})();
The amount of memory you'll save by doing this is pretty minuscule.
But every major browser today is DOM Level 1 capable; if you have backup code in your scripts to support Netscape 4, it is long past time to delete that. The baseline desktop browser right now is IE6.
The only browser in use today for which simple DOM manipulations are still a problem is IEMobile, versions prior to IEMobile 8/WinMobile 6.1.4. However this browser is so bad almost no scripts will work as-is; workarounds are required for pretty much everything.
Yes, the browser will parse the whole file. As for the "memory allocating" part. If you mean "allocate memory for all variables defined in the file" then no, it will only allocate it when the execution flow comes to that variables.
精彩评论