Created
September 18, 2012 17:07
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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