15 September 2009

Firefox caches JavaScript variables

It seems that Firefox (since 1.5) tries to cache not only the contents of a page, but JavaScript variables as well with something called bfcache. This also means that, among other things, the onload event will not fire if the user uses the Back button, or that variables set on the page will not be re-set and global scripts are not executed again. This can be important in AJAX-based applications, or if one tries to implement an analytics system on the page.

Apparently, defining an onunload event handler prevents Firefox from doing this kind of caching.

Why is a global variable undefined?

It took me some time to debug a script in which a global variable was undefined in a function, as I thought it was due to closures or other scope-related things. But the real cause was simple: if a global variable is re-declared as local in a function, then it is undefined in the local scope before its second declaration.

var x=1;

function myfunc(){
alert(x); // shows "1"

function myfunc2(){
// this will execute as "x" is undefined here
var x=2;
alert(x); // shows "2"

Checking if a variable is defined in JavaScript

In short, do not use "if(myvariable){ ... }" to check whether a variable is defined in JavaScript, because if it is not, the browser will return with an error and stop executing the script. The typeof operator can be used instead: "if(typeof(myvariable)!=='undefined'){ ... }".

According to this article, checking "window.myvariable" might be necessary, although the tests I've done do not show that "x" and "window.x" would behave differently.