Let's say you're waiting for Google Analytics to load. Now, you know that when Google Analytics loads, _gaq will be registered on the DOM. So, barring all other (better) asynchronous options, you can create a function that waits for the existence of _gaq:
waitForGaq = function(fn, attemptsLeft) {
var tick = attemptsLeft || 30;
if (typeof(_gaq) != 'object' || !_gaq._getAsyncTracker) {
//_gaq isn't registered yet
if (tick > 1) {
//recurse
setTimeout(function() {
waitForGaq(fn, tick - 1);
}, 100)
}
else {
//no ticks left, log error
log('failed to load window.gaq');
}
}
else {
//gaq is loaded, fire fn
fn();
}
}
So, any code needs to run AFTER _gaq is registered, you can add to the page thusly:
waitForGaq(function() {
//here's all my code...
});
To reiterate: recursing like this is only necessary if the script that you're adding doesn't offer an asynchronous way of interacting with the library. Google Analytics, for one, is kind of a moot example as it offers a cleaner approach:
http://code.google.com/apis/analytics/docs/tracking/asyncTracking.html