A new jQuery plugin
I have a new jQuery plugin available that helps a few issues, most notably WebKit returning incorrect element dimensions on DOM ready because it hasn't calculated the dimensions of descendent images yet. I call it waitForImages.
;(function($) {
$.fn.waitForImages = function(callback) {
if (typeof callback != 'function') {
throw 'Not a valid callback';
};
return $(this).each(function() {
var obj = $(this),
imgs = obj.find('img'),
imgsLength = imgs.length,
imgsLoaded = 0;
if (imgsLength == 0) {
return;
};
imgs.each(function() {
var image = new Image();
image.onload = function() {
imgsLoaded++;
if (imgsLoaded == imgsLength) {
callback.call(obj);
};
};
image.src = this.src;
});
});
};
})(jQuery);Usage is simple...
$(function() {
$('#something').waitForImages(function() {
alert('Images have loaded.');
});
});Update
I've just been getting the hang of GitHub, and I've taken the project source there.
I will be moving it to its own project page soon enough. It will probably coincide with a site update. I plan on a new site design and dropping the articles section and the WordPress/Kohana marriage (which is now on the rocks :P).
Comments
Alexander Dickson
Posted on Friday, 11th February 2011 @ 12:45am.@nickf
I wasn't aware of that bug, so thanks! I'll fix that for the next release.
nickf
Posted on Thursday, 10th February 2011 @ 8:34pm.Neat! It looks like that works even if the images have already loaded, too. The only suggestion I'd have would be to use `$.isFunction` instead of `typeof callback`. Webkit reports that regexes are functions for some bizarre reason.
Leave a Comment
Note: Your comment may require approval before it is posted to the site.