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 binding happens too late and the image has already loaded. Is there some way in jQuery to check if the image is already loaded?
Its obviously an intermittent issue, because sometimes the code is run before the image loads and sometimes its not.
$(function () {
var hasRun = false;
$('#image').bind('load', function () {
if ($(this).width() <= 0 || $(this).height() <= 0 || hasRun) return;
hasRun = true;
// do work here
}).trigger('load');
});
The code looks something like that. I've added the hasRun variable and a check against the height and width of the variable to ensure its loaded, and then added the trigger.
Is there a better way to do this? Is there some flag I can set with jQuery to tell it to run the function if the image is already loaded?