日期:2014-05-16  浏览次数:20398 次

JavaScript脚本何时执行?
想问一下,JavaScript脚本何时会得到执行。必须要调用的时候吗?比如说我写了如下测试程序
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>New Web Project</title>
  <script language="JavaScript">
  function test(){
  document.bgColor="black" //注意该两句代码的位置
  document.fgColor="blue"
  }
  </script>
   
  </head>
  <body onload="test()">
  测试document对象的属性
  </body>
</html>
如果换成如下:
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>New Web Project</title>
  <script language="JavaScript">
  document.bgColor="black" //注意该两句代码的位置
  document.fgColor="blue"
  function test(){
  }
  </script>
   
  </head>
  <body onload="test()">
  测试document对象的属性
  </body>
</html>
则document.bgColor="black"
document.fgColor="blue"
两句得不到执行

------解决方案--------------------
<script language="JavaScript">
document.bgColor="black" //注意该两句代码的位置
document.fgColor="blue"
function test(){
}
</script>
放到</body>后面
------解决方案--------------------
js是解释性语言,浏览器是按顺序加载整个网页的,加载到js时也是一行一行执行的,此时若对dom进行操作就会有找不到对象的异常,这是因为浏览器还没加载完整个网页,内存里自然没有这个对象,现在的浏览器dom,js,css啥的是多线程加载的所以js代码最好放在页面最后,或者写在window.onload里,等待dom元素加载完了再执行
------解决方案--------------------
探讨

引用:
<script language="JavaScript">
document.bgColor="black" //注意该两句代码的位置
document.fgColor="blue"
function test(){
}
</script>
放到</body>后面
为什么放到<body>后面就可以了呢?这两种方式有什么差别?