Page 1 of 1

is preloading images possible ??

Posted: Sat Feb 24, 2007 12:57 pm
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 !!

Posted: Sat Feb 24, 2007 1:45 pm
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>