/** * Author/Copyright: Benjamin Black (Benjamin_Black [_@AT_] condenast.com) * Licensed like jQuery: http://docs.jquery.com/License */ /** * This is a jQuery plugin for preloading images. I needed a way to preload images, and * wait for the images to be preloaded before taking action -- for example, before the * landing curtain fades in over the loading curtain, I want to wait for all the images * on the landing page to preload. But I wanted a way to do it that wasn't hard-coded, * specific to the number of images that needed to be preloaded, and without having to * manually bind preload events for each image. * * This plugin allows the user to preload an arbitrary number of images on a specific * container, by calling preload(img) with the image URL as a parameter. The preload is * queued, allowing the user to queue up several images to preload with repeated calls. * When preloading should begin, the user calles preload() without any arguments, and * the URLs in the queue are preloaded. As each image preloads, it fires a "preload" * event on the container for which it is preloaded, and when all images in the queue * have been preloaded, it fires a "preloaded" event on the container. If an image does * not exist (returns 404), or there is some other problem loading the image, it fires a * "preloaderror" event on the container. The "preload" and "preloaderror" events pass * the specific URL for the event, the URL queue, and the number of preloaded URLs as * event arguments, in addition to the event object. The "preloaded" event passes the * URL queue as the only event argument in addition to the event object; the number of * preloaded URLs is implicitly the length of the queue, in that case. * * Note that an image that fails to load is counted as a preloaded image, so it does not * stop the "preloaded" event from firing, even though it triggers a "preloaderror" event * on the container. * * If preload() is called before any URLs are queued, it is not treated as an error; it is * simply treated as if there are zero URLs in the queue, and the "preloaded" event is * triggered immediately. * * Assuming a
contains three large images that should be * preloaded before displaying it, this might be a coding pattern: * * $("#bigDiv") * .bind("preloaded", function() { * $(this).unbind("preloaded", arguments.callee); * $(this).fadeIn("medium"); * }) * .preload("bigImage1.jpg") * .preload("bigImage2.jpg") * .preload("bigImage3.jpg") * .preload(); */ (function($) { $.fn.preload = function(preloadUrl) { this.each(function() { var container$ = $(this); if (!Boolean(preloadUrl)) { var queue = container$.data("preload-urls"); if (!Boolean(queue)) { container$.trigger("preloaded"); return; } container$.removeData("preload-urls"); var preloaded = 0; $.each(queue, function(index) { var url = queue[index]; $("