I\'m trying to figure out how I can best attach a load event to an element, but be sure that it gets run. The issue comes when I bind to the load event of an img, but that bind
You can do this using .one() and .complete
like this:
$('#image').one('load', function () {
if ($(this).width() <= 0 || $(this).height() <= 0 || hasRun) return;
hasRun = true;
// do work here
}).each(function() {
if(this.complete) $(this).trigger('load');
});
.one() ensures the handler only executes once. The loop at the ends checks if the .complete
of the image is true, for example when it loads from cache or has already loaded for some other reason, and if it's true, triggers the load event...the .one()
prevents this from causing the load
code to fire twice as a result of this.