dweb Posted November 27, 2013 Share Posted November 27, 2013 Hi all Wondering if anyone can tell me why the following doesn't work; function img_checker() { $('#img1').load(function() { alert('loaded ok') }) } setInterval(function() { img_checker(); }, 500); I basically want javascript to check every X number of seconds to see if an image has been fully loaded any ideas? Quote Link to comment https://forums.phpfreaks.com/topic/284328-function-with-load/ Share on other sites More sharing options...
.josh Posted November 27, 2013 Share Posted November 27, 2013 It doesn't work because that's not how jQuery.load() works. .load() makes an ajax request to load a script, though there is an optional 3rd argument to specify a callback function when it has completed. Basically, there is no way to check if an image has been loaded or not, unless you specify a callback before the image is loaded. Example with creating image via js: var img = document.createElement("img"); img.onload = function() { alert('loaded okay'); } img.src = "http://www.google.com/intl/en_com/images/logo_plain.png"; document.body.appendChild(img); In this example, you can see that I have defined an .onload callback function (which should be defined before img.src is set, because the browser attempts to download (load) the image as soon as this is set). Same principle with an image tag, you can add a callback to the onload attribute: <img src="http://www.google.com/intl/en_com/images/logo_plain.png" onload="isLoaded()" /> <script type='text/javascript'> function isLoaded(that) { alert('loaded okay'); } </script> So basically, there are ways to attach an event handler to trigger when something is loaded, before it is loaded, but there is no way in javascript to determine whether or not it loaded, after it has already loaded. IOW there is no "isLoaded" type of property or function. Why not? I honestly don't know, and it's actually kind of annoying. If you have a browser addon like firebug to see the actual request and response, you can see if an image returned a 404 or timed out or something, so it's not like the browser doesn't know. It really doesn't seem like it would be that hard to expose that info to javascript. And it would be really useful, especially as far as making sure asynchronously loaded js scripts are executed in proper order. For scripts you can at least keep checking for the existence of some variable or object that's unique to that script (though you have to decide for yourself how long you should keep checking, since as I said, there's no way to know if it failed to load or is still loading or what), but there is no such work around for images. Quote Link to comment https://forums.phpfreaks.com/topic/284328-function-with-load/#findComment-1460372 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.