String.whenInDOM

I haven’t really had the time to make a post lately, as my conspicuous absence indicates. I’ve got an awesome gig at StylePage which keeps me busy and a number of side projects which steal the fleeting moments I can spare. While I’m not ready to peel back the curtains on any of my big projects, I think I’m just going to post some of the more useful utility functions I’ve built.

The first of which is String.whenInDOM which is a string primitive I could use to execute some code when a particular ID finally finds it’s way to the DOM. I use it for painless recursive asynchronous rendering. It also uses a a scaling interval, so if the result isn’t coming back quickly we don’t block up the browser, especially if we’re generating a large volume of these requests:

if(!String.whenInDOM){
if(!String.defaultReplacementTimeout)
String.defaultReplacementTimeout = 16384;
String.implement({
whenInDOM : function(
callback,
delayCallback,
timeoutCallback,
timeout,
counter
){
if(!timeout) timeout = String.defaultReplacementTimeout;
if(!counter) counter = 0;
if(!timeoutCallback) timeoutCallback = function(event){
throw(
'Element did not appear in DOM(\''+event.id+
'\') after '+event.time+'ms'
);
};
if(!document.id(this)){
// we want to get the DOM node when it appears
// so we're looking for a gradient falloff of intervals
// as it approaches timeout
var delayTime = Math.pow(2, counter);
if(delayTime >= timeout){
timeoutCallback({
id : this,
count : counter,
time : delayTime
});
}
counter++;
this.whenInDOM.delay(delayTime, this,
[callback, delayCallback, timeoutCallback, timeout, counter]
);
if(delayCallback) delayCallback({
count : counter,
time : delayTime
});
}else{
callback(document.id(this));
}
}
});
}
view raw String.whenInDOM.js hosted with ❤ by GitHub

It’s usage is pretty simple, just pass it a function to execute once the id is found. you can also optionally pass it a delay function as it’s second argument (executes each time we look for the id and it’s not found) and a timeout function (executes if we reach the ~16 second timeout (16384 ms))

'my_awesome_id'.whenInDOM(function(){
//do stuff here
});
view raw whenInDOM_ex.js hosted with ❤ by GitHub

That’s about it… till next time!


Warning: Illegal string offset 'echo' in /home/alloy/patternweaver.com/blog/wp-content/themes/hybrid/library/extensions/custom-field-series.php on line 82