When loading a page I have a Javascript function that gets information using AJAX. The function is used in the onload-event of the body tag to be executed when the page is loaded:
| <body onload="getStuff();"> |
The getStuff function gets data from a backend controller page using AJAX and when the data is returned asynchronously a div is updated with the data. So what happens in the JavaScript function when data gets back is:
| document.getElementById('divId').innerHTML = response |
The div is just a tag in the body section:
<body onload="getStuff();"> <div id="divId" /> </body> |
The problem is that sometimes (and this is to often to not care about it) the div don't get any content when the page is loaded. I am using Firebug so I can see that data is received via AJAX but it just isn't printed to the div. I tried to alert some text just to make sure that something was happening at this particular place in the code. And when I did, it suddenly displayed correctly.
If you have experienced this problem the explanation is that the div gets updated before it exist since the page is read from up to down. When you add an alert box it takes some extra milli seconds to execute and the div is defined and displayed before it gets updated with the ajax response.
But we don't want to have an alert there so what we do is make the function sleep just a little bit before we add the content to the div. This is accomplished using the setTimeout function. So replace the code in the onload-event of the body tag with this and it will start to work as expected:
| <body onload="setTimeout('getStuff()', 500);"> |
Where 500 is 500 milliseconds. Sometimes it takes longer time to open a site and sometimes shorter. So try with some different numbers here and get some slack in case of possible low performance but still make it an acceptable time for the end user.