问题
I have some functions that I am calling and they take some time (milliseconds), but I don't want the page to display until these functions have completed. Right now, I can tell that the page loads and then the scripts eventually complete.
Right now, I am calling the functions in the body onload.
Also, another issue I may have is that I need to access div elements in the html content, can I do that in my body onload function (getElementById('somDiv')?
Here is the workflow.
Make a call to getElementById('someDiv') to get an element from the page.
Invoke the function someFunc, this function is in the body onload=someFunc()
Wait until someFunc is finished
Display page to user once my function has completed.
回答1:
What you could do is keep your page content in a div
that is initially styled with display:none
. Then when your javascript code finishes, update the style on the div
to display:block
, e.g.:
<html>
<head>
...
<style type="text/css">
html, body, #body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
#body {
display: none;
}
</style>
<script type="text/javascript">
function myFunc() {
...
getElementById('body').style.display = 'block';
}
</script>
</head>
<body onload="myFunc();">
<div id="body>
...
</div>
</body>
</html>
Then Bob's your uncle: the page looks like it has delayed loading until after your script is finished.
回答2:
Functions that are called in the <body>
tag's onLoad
event are only fired when the DOM is loaded (however it does not wait for external dependencies such as JavaScript files and CSS to load), so you can be sure that when your someFunc()
function is called, (if attached to the <body>
tag's onLoad
event) the elements in the page have been loaded. If you want to access a DIV that is loaded in the page then you can be sure that it will have loaded when your someFunc()
function is called.
To solve your problem you could wrap then content of your page in a DIV, with the display
of it set initially to none
. Then when the page has loaded, your someFunc()
function is called. When it has finished executing, you can set the display
of your wrapper DIV to block
, so that it is visible to the user.
However, make sure that you make the user aware that the page is loading, and you do not simply show them a blank screen whilst your JavaScript is loading.
回答3:
The body's onLoad function is triggered when the DOM has completed loading - which implies that all HTML elements have been fully loaded. So your onload function itself should assume that everything is loaded and ready to go, since its very execution is under those guidelines.
来源:https://stackoverflow.com/questions/951945/javascript-have-body-onload-function-wait-until-scripts-have-completed