简体   繁体   中英

Fire javascript after images have loaded

I have a div that can be dynaimcally changed with an ajax script:

{
     var xmlHttp = GetXmlHttpObject();
     var url="/dashboard/ajax/images_pop_ajax.asp";
     if (!xmlHttp){
          alert ("Browser does not support HTTP Request")
          return
     }
     xmlHttp.onreadystatechange=function()
     {
          if (xmlHttp.readyState == 1)
          {
               document.getElementById("images_inner").innerHTML = LoadingAlert;
          }
          if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
          {
               var result = xmlHttp.responseText;
               document.getElementById('images_inner').innerHTML = result;
               window.onload = function(){AdjustColumns();}
          }
     };
     xmlHttp.open("GET", url , true)
     xmlHttp.send(null)
}

function GetXmlHttpObject()
{
     var objXMLHttp=null;
     if (window.XMLHttpRequest)
     {
          objXMLHttp=new XMLHttpRequest();
     }
     else if (window.ActiveXObject)
     {
          objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
     }
     return objXMLHttp;
}

When the images_pop_ajax.asp file runs it returns 8 images, which are then placed into the div tab id images_inner. Once this is complete, i want to adjust the columns of my page so everything is aligned. so I run this script:

function AdjustColumns()
{
     var ImgCol = document.getElementById('images_inner').offsetHeight;
     var ClassCol = 820;
     if (ImgCol > 574)
     {
          var ToAdd = eval(ImgCol - 574);
          document.getElementById('class_inner').style.height = eval(ClassCol + ToAdd) + 'px';
     }
}

The problem I have is that the AdjustColumns() script runs before all the images are loaded so consequently the columns dont line up. How can I get it to run, after the images have loaded?

Many thanks in advance,

neojakey

for each image you should add this event and wait for them when they are all loaded (use a counter)

   var counter = 0;
   var image = new Image();
    //attachEvent("onload") for ie
    image.addEventListener("load", function() {
                                   counter++;
    if(counter == 8) adjustColumns();
    }, false);
    image.src = "image.jpg";

beware though there are some times it doesn't work well, for example when the image is in the cache already.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM