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.
  • Virgilio Nemi

    Hi, Kjetil!

    I´m posting this comment here cause didnt´f find anywhere else aprpppriate to talk to you.

    I´m using your awsome converter lib (http://www.kjetil-hartveit.com/blog/10/hex-binary-decimal-octal-and-ascii-converter#Conv_InputType) in one project of mine, and got stuck with this problem:

    Having this Hex string converted to ASCII:
    74 65 73 74 65 20 73 74 72 69 6e 67 0a 0d

    And then returned to Hex, got this bug:

    74 65 73 74 65 20 73 74 72 69 6e 67 a d

    The last two characters has no leading zeros….

    Would you help me on this??? Thanks!!!