Tracking the Insertion of Javascript Components into the DOM Tree

thumb image-post

I occasionally find myself creating Javascript components that need to run some type of setup procedure - but only once the component exists and is visible within the DOM tree. Situations in which I run into this problem typically involve calculations that are dependent on a component's dimensions.

My experience has been that such a seemingly simple thing to track often isn't. The component in question may not be immediately inserted into the document... It may be created as part of an even larger component that won't be inserted until its own setup routines are complete.

To help solve this problem, I've put together the $.whenLive jQuery plugin, which you can find on GitHub:

https://github.com/tkambler/whenLive

$.whenLive allows you to track the DOM tree insertion of one or more elements, while placing an emphasis on performance. Where possible, $.whenLive leverages the relatively new requestAnimationFrame function, which you can learn more about here and here. In short, recurring functions that are invoked via requestAnimationFrame will:

  • Pause when an active browser tab becomes inactive and vice-versa.
  • Run at an interval that is optimized to match the speed at which the browser is able to update the DOM tree.

An example of how this plugin can be used is shown below.

var widget = $("<div>I am a nobody. Nobody is perfect. Therefore, I am perfect.</div>");
$(widget).onLive(function() {
    // Awesomesauce.
    var height = $(this).height();
    var width = $(this).width();
});
$("body").append(widget);