Creating dialogs on demand

In a previous article, I explained how to load a page into a dialog. The article focused on a simple solution to keep it easy to understand. However, that simplicity does come with a drawback; the page contents are loaded immediately after the document is ready, even if the user never opens the dialog. In this article, I’ll show how to load the page on demand while still only making a single request regardless of how many times the user opens the dialog.

On-demand page loading

In order to create the dialog on the first click, we’ll take advantage of jQuery’s .one() event binding method. .one() binds a handler to an event, but the handler is only ever run once. Immediately after the handler runs it unbinds itself, preventing further execution. We’ll adapt the example from the previous article to take advantage of .one():

$(document).ready(function() {
	$('#page-help').each(function() {
		var $dialog = $('
'); var $link = $(this).one('click', function() { $dialog .load($link.attr('href')) .dialog({ title: $link.attr('title'), width: 500, height: 300 }); $link.click(function() { $dialog.dialog('open'); return false; }); return false; }); }); });

Adding the final touch

Now that we’ve got our dialogs loading on demand, we need to account for network latency, slow connections, etc. Previously we were loading the page contents before the user ever saw the dialog, so any delay was hidden. A simple solution for this is to just show a loading image inside the dialog until the page contents are loaded. We’ll load this image immediately on document ready to make sure that it’s ready for use when the user clicks the link to open the dialog. Loading images are generally very small in terms of file size and they can be cached by the user, so the overhead of loading the image up-front is negligible.

$(document).ready(function() {
	var $loading = $('loading');

	$('#page-help').each(function() {
		var $dialog = $('
') .append($loading.clone()); var $link = $(this).one('click', function() { $dialog .load($link.attr('href')) .dialog({ title: $link.attr('title'), width: 500, height: 300 }); $link.click(function() { $dialog.dialog('open'); return false; }); return false; }); }); });

View this example in a new window