Generic and reusable replacement for $(document).ready()
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.



Traditionally different JavaScript UI components (such as tabs, tooltips, rich editors) in jQuery applications are initialized inside of the DOM onload event handler with something like this

$(function() {
  $(".tabs").each(function() {

There are two issues which commonly arise with such approach.

  1. One of the onload handlers throws exception. The rest of the handlers are not executed. Mostly that's undesired since it could mean that single exception from some third-party library just disabled half of your JavaScript code.

  2. There are multiple sources of DOM elements nowadays, most importantly the elements loaded with AJAX and generated by templating. These elements need to be initialized in the same way elements present when onload event fired were initialized.


See full example in example.html.

Add to <head>

<script src="jquery.selector_initializers.js" type="text/javascript"></script>

Now register initializer with

$.addInitializer(selector, function_name, function_arguments, ...)

$.fn.applyInitializers then will use selector and call function_name with function_arguments on every element matched by selector.

Or more generic form


$.fn.applyInitializers will call function passing container (with elements awaiting initialization) as this.

For example, to register jQuery Tools Tooltip and Facebook FBML tags initializers

// jQuery Tools Tooltip
$.addInitializer(".trigger", "tooltip", { position: "bottom right", opacity: 0.7});

// Facebook FBML
$.addInitializer(function() { FB.XFBML.Host.parseDomElement(this[0]); } );

Then whenever DOM tree containing tooltips or Facebook tags comes into existence call $.fn.applyInitializers like

$(function() {
  // initialize on page load

// add dynamic content to #dynamic container
$("#dynamic").append("<fb:profile-pic uid='1335992023' />");

// initialize dynamically added content

Similar Projects

Dean Edwards proposes the solution based on custom events in Callbacks vs Events article. It's cool, but complex. selector_initializers just wraps each handler in try ... catch block reporting exceptions where windows.console is available.

Very similar project

More ambitious. Eliminates manual applyInitializers calls by hooking into jQuery DOM manipulation methods