Sometimes images take some time to render in the browser. I want to show a busy image while the actual image is downloading, and when the image is downloaded, the busy image is removed and the actual image should be shown. How can I do this with JQuery or any javascript?
You can do something like this: // show loading image $('#loader_img'). show(); // main image loaded ? $('#main_img').
Just make a new image via javascript, and only show the image after the onload has fired. This will make sure you don't see any partial rendering of the image. Note that at least chrome will display the "web page loading spinner" in its interface until the image is loaded.
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.
The image is considered completely loaded if any of the following are true: Neither the src nor the srcset attribute is specified. The srcset attribute is absent and the src attribute, while specified, is the empty string ( "" ). The image resource has been fully fetched and has been queued for rendering/compositing.
Just add a background image to all images using css:
img { background: url('loading.gif') no-repeat; }
You can do something like this:
// show loading image $('#loader_img').show(); // main image loaded ? $('#main_img').on('load', function(){ // hide/remove the loading image $('#loader_img').hide(); });
You assign load
event to the image which fires when image has finished loading. Before that, you can show your loader image.
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