Thursday, March 8, 2007

Javascript - create arbitrary events

While debugging a JavaScript error that only came up on slower connections, I came across a free proxy that allows you to simulate slower internet connections: sloppy.

This led to the source of the problem -- prototype, scriptaculous, and a large json object were dynamically being brought into the page (by creating a script tag in the head). However, varying load times could cause these three to load in various orders. This called for some way to set up arbitrary events that triggered arbitrary functions.

Here is what I came up with:
wait_around = function(test_function, next_function){
if ( eval(test_function) ) {
eval(next_function);
} else {
setTimeout(function(){travidiaTrafficDriverAdvList.wait_around(test_function,next_function);}, 100);
}
}

This allows you to create arbitrary events.

execute some_function after Prototype is loaded:
wait_around('typeof Prototype != "undefined"', “some_function()”)

execute another_function after someJsonVariable is loaded:
wait_around('typeof someJsonVariable != “undefined”’, “another_function()”)