how to check if image loaded or not in javascript?
If you are having a webpage with large sized images, you would notice the browser taking long time to load those images and showup. A good idea would be show a loading animation until large photos load.
There is a way to check whether the images have been loaded or not in javascript. Using the Image() object is a good method to cache large images.
You can use onload function to trigger a event after loading is complete.
objImg = new Image();
objImg.src = 'photo.gif';
objImg.onload = function() {
/// do some work;
}
Another way of checking is use complete property
objImg = new Image();
objImg.src = 'photo.gif';
if(!objImg.complete)
{
/// do other work;
}
Hope this helps if you are a javascript programmer.
Similar Posts:
- how to call a php script from javascript?
- how to change div content in javascript?
- A Simple WYSIWYG Editor in Javascript
- Eclipse IDE loading slow?
- iFrame in javascript wont work in Firefox [solved]
- How to get image attachment ID in WordPress?
- Implementing Secure File Upload in PHP
- Optimizing MySQL Rand() against Slowdowns
- Lightweight PHP WYSIWYG HTML Editor
- Single/double quotes causes error in mysql INSERT query!





July 9, 2009
Not all browsers support onload or complete. For complete cross-browser compatibility, check if the width or height are greater than 0.
July 14, 2009
Awesome code of Java Script. Thanks for letting us know.
I also thought to mention one very minor thing here. In the code above
objImg.onload = function {
/// do some work;
}
Parenthesis “()” should be added after the keyword “function” above. I know almost everybody is aware of it eventhen thought to mention it here.
Many thanks for this great help.
Gaurav Arya
July 14, 2009
very well spotted Gaurav!
April 16, 2010
You have to put onload event handler declaration before src property change because IE wouldn`t process it well.