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?
Preload the image and replace the source of the <img /> after the image has finished loading. Show activity on this post. You can use the complete property to check if the image has finished loading.
The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
Description. The onload property of an Image object specifies an event handler function that is invoked when an image loads successfully. The initial value of this property is a function that contains the JavaScript statements specified by the onload attribute of the <img> tag that defined the Image object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With