Skip to content

Instantly share code, notes, and snippets.

@localpcguy
Created September 18, 2012 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save localpcguy/3744340 to your computer and use it in GitHub Desktop.
Save localpcguy/3744340 to your computer and use it in GitHub Desktop.
executeOnDomNodeLoaded polls the DOM repeatedly until the DOM node is in the DOM, and then executes the callback
function executeOnDomNodeLoaded(node, func) {
// This function will check, every tenth of a second, to see if
// our element is a part of the DOM tree - as soon as we know
// that it is, we execute the provided function.
var findUltimateAncestor = function(node) {
// Walk up the DOM tree until we are at the top (parentNode
// will return null at that point).
// NOTE: this will return the same node that was passed in
// if it has no ancestors.
var ancestor = node;
while(ancestor.parentNode) {
ancestor = ancestor.parentNode;
}
return ancestor;
},
isInDOMTree = function(node) {
// If the farthest-back ancestor of our node has a "body"
// property (that node would be the document itself),
// we assume it is in the page's DOM tree.
return !!(findUltimateAncestor(node).body);
};
if(isInDOMTree(node)) {
func();
} else {
setTimeout(function() { executeOnDomNodeLoaded(node, func); }, 100);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment