PDA

View Full Version : Loading images with JS


AlwaysHappy
05-07-2003, 10:16 AM
Hello,
I need my JavaScript to load the images after the page has loaded. This will give the illusion of faster page loading.

I'm pretty sure that the function which writes the img tag needs to activate before the page has loaded, but only load the images once an OnLoad event triggers.

This is what I had done:
<script language="javascript">
function loadI() {
document.write("<img src=img.jpg>");
}
</SCRIPT>
Later in the HTML code I would call the loadI function but this would display only the image, not the rest of the page. I don't know how (but I'm trying to) to incorporate an OnLoad event, which should then activate the function which writes the img tag into the document without erasing it with the tag itself. Am I on the right track trying to do this?

liorean
05-07-2003, 12:30 PM
Include your image tags in the html code first - then you simply change their src attribute when you want to:
function fnImgLoad(sSrc){
return ((new Image).src=sSrc);
}


window.onload=function(){
var
aSrc=[[string ImageAddress],...],
i=aSrc.length,
j=i;
while(i-->0)
ImgLoad(aSrc[i]);
while(i++<j)
document.images[i]=aSrc[i];
}

AlwaysHappy
05-10-2003, 05:06 PM
Dear liorean,
Thank you very much for taking the time to reply.
Unfortunately, I don't yet know how to implement your code into a working web page with images.

While I DO have basic JS skills, and have used them for quite some time, this script is too complex for me. The 2 lines of code I don't understand are:
aSrc=[[string ImageAddress],...],
and
return ((new Image).src=sSrc);

liorean
05-10-2003, 05:32 PM
Let's see:return ((new Image).src=sSrc);This could be written as:var oImg=new Image;
oImg.src=sSrc;
return sSrc;In other words, it creates an image object, loads the image you want, and then returns the address of that image. I've simply written it all in one operation instead of several.

As for aSrc=[[string ImageAddress],...],, the [] is the syntax for an array literal, as used in JavaScript and several other languages. You could write that like this instead:aSrc=new Array([string ImageAddress],...),

The [string ImageAddress] is the standard way of saying "insert a string containg an image address here". In other words, if you see [type description] in a code listing, you know you should replace it with whatever it represents when you write the code. The ', ...' indicate that you can insert as many such as you require.

Which means, in other words, no matter how you specify it aSrc should be an array of image addresses, that you then load after the html has been parsed.


HTH