开发者

Javascript delayed image loading

I am trying to delay the loa开发者_运维问答ding of images using plain JS. my method to do this is by giving empty src field for the image and inserting the image url into a temp attribute called "lang" as used in the example below. ie > <img lang="logo.gif"> instead <img src="logo.gif">. When pressing a button the js below is initiated to insert into src attr the value of the dummy "lang" attr.

function showimagesunderdiv(divid)
{
 tr = document.getElementById(divid);
 pics=tr.getElementsByTagName('img');
 for(i=0;i<pics.length;i++)
  {
  if(pics[i].lang)
   {
   pics[i].src=pics[i].lang;
   pics[i].style.display='';
   }
  }
}

While this works is Chrome and FF, IE is doing problems. Any idea?


Maybe this:

<html>
<body>
<p>Images:</p>
<img name=image0>
<img name=image1>
<img name=image2>
<img name=image3>
End of document body.
</body>
<script type="text/javascript">
function LoadImage(imageName,imageFile)
{
  if (!document.images) return;
  document.images[imageName].src = imageFile';
}
LoadImage('image4','number4.gif');
LoadImage('image5','number5.gif');
LoadImage('image6','number6.gif');
LoadImage('image7','number7.gif');
</script>
</html>

Or this:

<html>
<body>
<p>Images:</p>
<img name=image0 onLoad="LoadImage('image1','number1.gif')">
<img name=image1 onLoad="LoadImage('image2','number2.gif')">
<img name=image2 onLoad="LoadImage('image3','number3.gif')">
<img name=image3>
End of document body.
</body>
<script type="text/javascript">
var loadingImage = false;
function LoadImage(imageName,imageFile)
{
  if ((!document.images) || loadingImage) return;
  loadingImage = true;
  if (document.images[imageName].src.indexOf(imageFile)<0)
  {
    document.images[imageName].src = imageFile;
  }
  loadingImage = false;
}
LoadImage('image0','number0.gif');
</script>
</html>

I know it is not a correction of your code but I cant see whats wrong...

This is a very compatible solution!

Hope it helps! resource:

http://www.cryer.co.uk/resources/javascript/script3.htm


Give each image tag an ID, store the IDs and URLs in an array:

imagesToLoad = [["imgId1", "http://..."], ["imgId2", "..."], ...];

And use:

function showimages(imageList)
{
  for(var x = 0; x < imageList.length; x++) {
    document.getElementById(imageList[x][0]).src = imageList[x][1];
  }
}

showImages(imagesToLoad);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜