Having read other people's questions I thought
window.onload=...
would answer my question. I have tried this but it executes the code the instant the page loads (not after the images load).
If it makes any difference the images are coming from a CDN and are not relative.
Anyone know a solution? (I'm not using jQuery)
To determine whether an image has been completely loaded, you can use the HTMLImageElement interface's complete attribute. It returns true if the image has completely loaded and false otherwise. We can use this with naturalWidth or naturalHeight properties, which would return 0 when the image failed to load.
In jQuery when you do this: $(function() { alert("DOM is loaded, but images not necessarily all loaded"); }); It waits for the DOM to load and executes your code. If all the images are not loaded then it still executes the code.
Image() The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document. createElement('img') .
Here is a quick hack for modern browsers:
var imgs = document.images, len = imgs.length, counter = 0; [].forEach.call( imgs, function( img ) { if(img.complete) incrementCounter(); else img.addEventListener( 'load', incrementCounter, false ); } ); function incrementCounter() { counter++; if ( counter === len ) { console.log( 'All images loaded!' ); } }
Once all the images are loaded, your console will show "All images loaded!".
What this code does:
incrementCounter
functionincrementCounter
will increment the counterHaving this code in a cross-browser way wouldn't be so hard, it's just cleaner like this.
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