Question

I require to show a loading icon when I am assigning a URL to an image element. I have looked at the other questions on this site which only details about how to show graceful pre-loader for images when loading a page. What I require is to show the pre-loader after the page is loaded. There are 2 scenarios to what I am looking for which I have explained below.

  1. I dynamically create an DOM Image Element and assign a URL to this Element. While doing so, it takes about a 2-3 seconds to show the image on the element and the area goes blank for those 2-3 seconds. What I would need to do is to show a pre-loading icon and hide it once the image has been loaded.

  2. I dynamically create an DIV Image Element and assign a URL to background:url(). While doing so, it takes about a 2-3 seconds to show the image on the element and the area goes blank for those 2-3 seconds. What I would need to do is to show a pre-loading icon and hide it once the image has been loaded.

How can I achieve showing the preloader for both the scenarios?

Was it helpful?

Solution

You can do it by using the load() event.

When you first go to start the loading, change your image to show the preloader, or however you want to do it. Also, attach a "load" event to it.

Then, once the image is loaded, remove your preloader and show the image.

You'll need to do a similar trick for the CSS related one (the background url). What you can do is load the image directly (by creating a new Image()), while settings the background url to your preloader icon.

Then, once the image is loaded, do the switch. Since the browser only loads an image once regardless where it is used, it should have the same effect.

OTHER TIPS

There's a good tutorial and screencast on doing this at: http://jqueryfordesigners.com/image-loading/

Although in some browsers (like older versions of IE) the .load() function doesn't work so well for images, in which case you can use: https://github.com/JessThrysoee/jquery.imageload instead of .load() for a more consistent cross browser experience.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top