Categories
Javascript JQuery

Preloading Images with JavaScript

Sometimes in a complex javascript-application you want to display an image when it is fully loaded. Until then you want to show for example a common loading-imageAjax Loading Image. In this case the best solution is to load the image in background, and then show it to the use. For that you can use the Image-Class provided by the browsers.

This class is the used Class at img-Tags. So you have all known properties, like “src”. With the onload-Event you can then check, if the image was fully loaded or not. An example would be:

?View Code JAVASCRIPT
1
2
3
var image = new Image();
$(image).load(function () { alert("picture is fully loaded."); });
image.src="http://www.javahelp.info/wp-content/uploads/2009/11/Bild-80-300x64.png";

In the example I use JQuery for event-handling, because this is more comfortable as the normal event-method of JavaScript.