I wonder if anybody can give some advice on this. I am not too experienced with asynchronous code. I am trying to load information from other pages on our website onto the home page, for a "recent projects" list. I want to be able to supply a simple list of names corresponding to web pages and this script is supposed to go to load the the first H1 tag and first image from each page and package them in some HTML which I define with the "template" variable. The thing is, sometimes it works and sometimes it doesn't and I think it has to do with the asynchronous loading.
Let me explain the code before I show it. I have an array holding each "job" name. There are two .load calls that are performed for each item in the array: one to load the title and one to load the image. The titles always load fine but frequently the image fails to load. At the end of the callback function for each .load I call a checkLoading function to see if everything is done loading so I can display it. The really bizarre thing is that when I use Firebug and put a breakpoint inside the .load callback for the images and then go check the HTML tab the first time it breaks, it shows me that the last image has already been loaded but none of the other ones. By my understanding that should be totally impossible! Is Firebug just lying to me? First some variables are defined in the head. <script language="javascript" type="text/javascript"> var list = ['johnston_heights','queen_e_royals','janice_churchill','earl_m_stationary']; var title; var src; var url; var tcount = 0; var scount = 0; var html = new Array(list.length); var template = "<div class='preview'><a href='{url}'>"; template += "<img src='{src}' alt='{title}'/>"; template += "<span class='hoverBox'> </span><span class='hoverText'>{title}</span></a></div>"; </script> Then this code seems to need to be in the body. <script language="javascript" type="text/javascript"> $(document).ready( function() { for(job in list){ html[job] = template; url = "portfolio/portfolio_pages/"+list[job]+".html"; html[job] = html[job].replace("{url}",url); $("#recent").append("<p class='temp' id='temp"+job+"'></p>") } for(job in list){ url = "portfolio/portfolio_pages/"+list[job]+".html"; //title $("#temp"+job).load(url + " #content h1:first",null,function(){ title = $("#temp"+tcount+" h1")[0]; title = ($(title).html()); html[tcount] = html[tcount].replace(/\{title\}/g,title) checkLoading(); tcount++; }); //image source $("#temp"+job).load(url + " .thumbnails img:first",null, function() { src = $("#temp"+scount+" img")[0]; src = ($(src).attr("src")); src = src.replace("..","portfolio"); html[scount] = html[scount].replace("{src}",src) checkLoading(); scount++; }); } }); function checkLoading(){ //console.log(html); if(tcount+scount >= list.length*2-1 ){ //$("#recent").html(""); for(preview in html){ $("#recent").append(html[preview]); } $("#recent").show(); }; } </script>