javascript onload事件和html页面中的普通脚本之间的区别 [英] difference between javascript onload event and plain script in the html page
问题描述
这两段代码有什么区别
样本1:
< script type =text / javascript>
函数myfunc(){
alert('hi');
}
window.onload = myfunc;
< / script>
样本2:
< script type =text / javascript>
alert('hi'); //没有使用函数
< / script>
两段代码都成功执行。提前谢谢。
window.onload
使得所有DOM元素在脚本运行之前加载 - 也就是说,如果您的脚本修改或使用DOM元素,然后它应附加到 window.onload
(或框架中的等效内容)。如果它独立于DOM,您可以使用它们。有关详细信息,请参阅 Mozilla开发人员网络页面。请注意,无法从 window.onload
运行的内联脚本可以在解析器到达时运行 - 它不会等待加载其余的DOM。 / p>
What is the difference between these two pieces of code
Sample 1:
<script type="text/javascript">
function myfunc () {
alert('hi');
}
window.onload = myfunc;
</script>
Sample 2:
<script type="text/javascript">
alert('hi');//no function used
</script>
both pieces of code execute successfully.Thanks in advance.
The window.onload
makes it so that all DOM elements are loaded before the script runs - that is, if your script modifies or uses DOM elements, then it should be attached to window.onload
(or something equivalent in a framework). If it is independent of the DOM you can use either. Refer to the Mozilla Developer Network page for more information. Note that inlined scripts that don't run from window.onload
can run once the parser reaches it - it doesn't wait for the rest of the DOM to be loaded.
这篇关于javascript onload事件和html页面中的普通脚本之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!