javascript image preloading

Image Preloading with JavaScript

Now a days web visitor prefers to see fancy page designing .when designing most attractive web page ,it becomes must use lot of images ,back grounds ,animation effects.
When page becomes more attractive with lot of images, it takes time to load all the images and it consumes the user bandwidth.
Generally each embedded page elements like images, audio, video objects are loaded when browser makes HTTP request to server. When it comes to tri state buttons, mouse over image, loading large images, the user wait to see effects at first time. After loading first time browser will cache the image.

Image Object

So over come this first time loading of image we use JavaScript image object for loading.
We create an image object instance before web page body loaded, so the browser will make HTTP request before the required mouse over, image hover effect, tri state buttons.
Most advanced browser now a days use DOM, so it works on all browser.

CSS and Sprites

for javascript disabled browsers we can use css & sprite image preloading.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>image preload</title>
<script type="text/javascript">
function preload_images(){
	img_length=preload_images.arguments.length;
	for(var i=0;i<img_length;i++){
		src=preload_images.arguments[i];
		img=new Image();
		img.src=src; //here we make http request
	}
}
// we are calling the function there by making HTTP request for images before page body loads
//here we use function argument property for multiple images
//remember all the image paths can be absolute or relative
preload_images('myimg.gif','urimg.jpg');
</script>
</head>
<body>
</body>
</html>

download source code

image-preloading-javascript-source-code

3 thoughts on “javascript image preloading

  1. Pingback: Image preloading tutorial with css and image sprites | Php Developent

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">