views:

55

answers:

2

I'm developing a site in javascript and jquery. Sometimes when I refresh I just get different random errors in firebug. What's the deal?

edit: I'm getting errors like a variable isn't defined, when clearly it is and working, and when i refresh again, the error is gone..

using Firefox V3.5.5 Firebug V.1.5.3 and I'm primarily working with jQuery 1.4.2

+1  A: 

Most common cause is that you're trying to execute Javascript before the DOM is loaded and thus before all HTML elements are available in the DOM tree, which in turn may cause that simple calls like document.getElementById(id) and jQuery's $(selector) may return undefined elements. That it sometimes works is pure coincidence and a matter of timing.

You need to ensure that any Javascript/jQuery code which is supposed to be executed during page load and relies on the availability of the elements in the DOM tree, also really get executed after the DOM is loaded. In plain vanilla JS you can do so:

window.onload = function() {
    document.getElementById(someId);
}

and in jQuery:

$(document).ready(function() {
    $(someSelector);
});
BalusC
+2  A: 

OK. While it's more or less impossible to give a reasonable solution to such a general question, I'll just add my 2 cents' worth:

One possible source of "undefined variable" errors comes from including several scripts, which may or may not always load and execute in the same order. If you define a variable in one script (let's call that script declare.js) and use it in another (let's say use.js), and use.js is executed before declare.js, then you will get such an error. If the scripts execute the other way around, everything will appear fine.

If you're interested in this very topic, have a look at e.g. Steve Souders' book Even faster web sites, published by O'Reilly. More specifically, look at the chapter about non-blocking script loading.

stakx
very interesting, thanks for your input.
Matt Nathanson