Polling for loaded content instead of simple setTimeout
Date : 2008 05 14 Category : Tech & DevelopmentHave you ever found yourself doing little setTimeout calls as you wait for content to be loaded asynchronously? It seems to happen pretty frequently, and Paul Irish has created a simple utility to help run code when the library you need is loaded.
With his executeWhenLoaded(function, objects, that, must, be, present) you can do something like this:
PLAIN TEXT JAVASCRIPT:executeWhenLoaded(function(){ console.log(session.data); }, 'session'); // session will return a value when the whatever preceding functionality is done.
The implementation is simply:
PLAIN TEXT JAVASCRIPT:function executeWhenLoaded(func){ for (var i = 1; i<arguments.length; i++){ // for loop starts at 1 to skip the function argument. if (! window[ arguments[i] ]) { setTimeout(arguments.callee,50); return; } } func(); // only reaches here when for loop is satisfied. }