How to ensure that a Javascript function is finished before moving on to the next line in the HTML code.
For eg : I am having a Javascript code in main() and calling tht as shown below. Before this finish off, the next line of HTML code like loading a JPEG is showing up in the webbrowser.
Is there any way I could ensure the main() call is executed completely.
<script language="JavaScript" type="text/javascript"> main();</script>
As some of you guessed correctly,There is an asynchroous call within the main() which uses a XMLHTTPRequest() to get some of the values I need to form the webpage. The function main is a s below
function main()
{
var requestor = new net.Requestor("admin/getparam.cgi?mainvideostream&codectype", CurrentHandler);
}
and net.Requestor=function(url,onload,onerror,method,params,contentType)
within this thers is and XMLHTTPRequest(…)
And the Currenthandler is another function which deals with the response from the requset.
function CurrentHandler()
{
settings = this.req.responseText.split("\n");
for(var j=0; j<settings.length-1; j++)
{
var currentST= settings[j].split("=");
name = currentST[0];
value = currentST[1];
switch(name)
{
case "mainvideostream": cur_camid = value; break;
case "codectype": stream = value; break;
}
}
mainSection();
}
So I have to find out the stream variable before loading the page.
The short answer is no, there is no (safe, standards compliant) way to stop the page from loading while your script runs.
Typically, this is worked-around in one of two ways:
Hide the elements on the page that you don’t want to appear to be loaded by setting their CSS
displayproperty tonone. Add a command at the end of your script to reset the display property on those elements.Move the elements you do not want to initially load into a separate HTML file. At the end of your script execution, make an AJAX call back to the server to get that second file and load it into the appropriate point within your main file.