javascript onload事件和html页面中的普通脚本之间的区别 [英] difference between javascript onload event and plain script in the html page

查看:69
本文介绍了javascript onload事件和html页面中的普通脚本之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两段代码有什么区别



样本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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆