Simple helping function for managing dependencies in JavaScript

Here’s a very simple helping function that can be used to manage arbitary dependencies in your script.

The dependency check is defined with a callback so you can write dependencies for when DOM is loaded, a script is ready or anything else you’d need.

Features:

  • Define your own dependency checks – generic and reusable code snippet
  • Simply pass in the callback you want to execute when the dependency is ready
  • User-defined interval for checking dependency
  • Max tries functionality to prevent infinite loops

Usage:

// Let's say you want to do something when the DOM is ready

var callback = function() {
  $( "#container" ).append( "<p>Succesfully loaded DOM.</p>" );
}

doIfDOMisReady( callback );

// Or with the generic function do:

doIfReady( function() { return jQuery.isReady; }, callback, 150, 10 )

//=====================================

// Do something when an external API is ready

var callback = function() {
  alert( 'API ready' );
}

doIfReady( function() { return window._gaq !== undefined; }, callback, 150, 10 )

Source code for helping function(s):

function doIfReady(checkCallback, readyCallback, interval, maxTries) {
	interval = interval || 150;
	maxTries = maxTries === undefined || maxTries === null ? 8 : maxTries;

	if ( checkCallback() ) {
		readyCallback();
	} else {
		if ( maxTries ) {
			setTimeout( function() {
				doIfReady( checkCallback, readyCallback, interval, maxTries-1 );
			}, interval );
		}
	}
}

function doIfDOMisReady(callback) {
	// PS! $.isReady is an undocumentet property in jQuery, use with caution
	doIfReady( function() { return jQuery.isReady; }, callback, 150, 10 )
}
This entry was posted in JavaScript and tagged , . Bookmark the permalink.