is preloading images possible ??

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

is preloading images possible ??

Post by PHPycho »

Hello friends !!
My Question:
suppose i have to show the photo gallery,
and suppose it has 5 image links
Refer the following:
----------------
|
| Image preview of links 1 -5 goes here here..
|
|
------------------
Links 1 | 2 | 3 | 4 | 5
when clicked on link1 preview of 1 show appear and similarly up to 5.
What i want to do?
I want to display the images without loading when clicked on the link
and i suppose it can be done using javascript, problem is how to preload the
images so that when the link is clicked image should instatly appear in the preview section.
Is there any idea to perform this ?
I would be very greatful for the soultions.
Thanks in advance to all of YOU !!
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

You need to use JavaScript. The idea is that you create Image() objects in the <head> of the page but don't actually display them. When you give an Image() object a "src" property in JavaScript, it instantly downloads the image and holds it in that variable. Now, you can just re-assign the "src" of a real image and it will instantly change because the image is cached.

In the <head> inside a <script> block.

Code: Select all

//Define some paths
var imgSrcs = new Array("images/foo.jpg", "images/bar.jpg", "images/zip.png");
//Load them into image objects
var imgObjs = new Array();
for (var i in imgSrcs) {
    imgObjs[i] = new Image();
    imgObjs[i].src = imgSrcs[i];
}

//Make a function to change the currently viewed image
function setImg(i) {
    document.getElementById("myimage").src = imgObjs[i];
}
In the <body>.

Code: Select all

<img src="images/default.jpg" alt="Image viewer" id="myimage" />
<br />
<a href="javascript:setImg(0);">Image 1</a> |
<a href="javascript:setImg(1);">Image 2</a> |
<a href="javascript:setImg(2);">Image 3</a>
Post Reply