jQuery: the load() event has been deprecated. Now what?

jQuery: the load() event has been deprecated. Now what?

The load() event has been deprecated in jQuery but web developers still use this event to preload images.

The .load() event in jQuery has been deprecated, mostly due to the inconsistent and incompatible results that you get when you try to make this event work in a cross-browser fashion on images. Anyway, web developers insist with using this event in many contexts. A possible solution to be applied to image preloading is to stick to the old-fashioned DOM Level 0 events, as shown below.

The following utility object, found on Snipplr, takes two arguments, namely an object literal or array containing image paths and a callback function to be executed after all the images have finished loading.

This approach follows the old-school's way used to preload images back in the 90's: it creates an Image object and set progressively its src property to the path found in the first function's argument.

It also binds the onabort and onerror handlers to the newly created image in order to track and log the progress of the loading routine.


var preloadImages = function(list, callback) {
		if (typeof(list) == 'object' && typeof(callback) === 'function') {
			var callbackAfter = list.length;
			var preloadInterval = window.setInterval(function() {
				if (callbackAfter === 0) {
					window.clearInterval(preloadInterval);
					callback();
				}
			}, 100);
			$.each(list, function(index, image) {
				list[index] = new Image();
				list[index].onload = function(result) {
					callbackAfter--;
				};
				list[index].onabort = function(result) {
					console.log(result);
				};
				list[index].onerror = function(result) {
					console.log(result);
				};
				if (!image.match('http://')) {
					image = image;
				}
				list[index].src = image;
			});
		}
};

I don't know if this code is actually effective or not. Testing a similar code on a web app viewed on an iPad with a cellular connection produced no real results, in the sense that the perceived loading performance was not so evident.

The problem is that images may be huge in size, so that setting an interval to cache one image at time is practically impossible. I think many developers assume that their web apps are viewed on mobile devices with a broadband or Wi-Fi connection. They seem to ignore other ways users have to surf the web via a mobile device.