Javascript:使用body onload函数等待脚本完成 [英] Javascript: Have body onload function wait until scripts have completed
问题描述
我有一些我正在调用的函数,它们需要一些时间(毫秒),但我不希望页面显示,直到这些函数完成。现在,我可以告诉页面加载然后脚本最终完成。
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.
现在,我正在调用正文中的函数onload。
Right now, I am calling the functions in the body onload.
另外,我可能遇到的另一个问题是我需要访问html内容中的div元素,我可以在我的身体onload函数中执行此操作(getElementById('somDiv')?
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')?
这是工作流程。
-
拨打getElementById('someDiv) ')从页面获取一个元素。
Make a call to getElementById('someDiv') to get an element from the page.
调用函数someFunc,这个函数在body中onload = someFunc()
Invoke the function someFunc, this function is in the body onload=someFunc()
等到someFunc完成
Wait until someFunc is finished
我的功能完成后向用户显示页面。
Display page to user once my function has completed.
推荐答案
您可以做的是将您的网页内容保存在 div中
最初的样式是 display:none
。然后当你的javascript代码完成时,更新 div上的样式
到 dis play:block
,例如:
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.
这篇关于Javascript:使用body onload函数等待脚本完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!