Image onload event after image has loaded
开发者_运维问答I have a script that attaches onload event handlers to all the images on a page, however because it's a GreaseMonkey script it can only run after the images are there, so some of them may have already loaded, is there a way to trigger the onload event if the image is already loaded?
If you're not adverse to using a framework such as jQuery, there's a triggerHandler() function that should do what you need.
You'll need a test to check whether or not the image has been loaded in your script (should be able to find details on how to do this using Google) - if it hasn't been loaded, simply attach the onload event handler; if it has been loaded, you can either attach the onload event handler and then trigger it using jQuery's triggerHandler() function, or execute the code/function that would have been executed by the onload event handler - which is easiest likely depends on what your onload event handler does.
It's an onload event. I wouldn't have thought that event would fire more than once.
You could attach your script to the body / document onload event and loop through all the images and attach your event handlers then, perhaps.
I've just had the same issue and Google takes me there.
I didn't want to use jQuery, so I searched for another solution. In the end, in my case, I simply changed the image's "src" attribute to any dummy picture (e.g. 1pix.png) just before setting the right image in "src", to force a reload for each image. Of course, this is not a bright idea if you have large images and/or if you frequently load images... But in my case it's ok I guess, I only need to load the big actual image only once (moreover, I think that the underlying browser cache mechanism avoids a real image reloading...).
Hope it can help others!
PS: It seems to be near to @Bugster workaround but I didn't really understand it!
精彩评论