您的位置:首页 > Web前端 > JavaScript

写在body的js跟写在head的区别

2014-02-21 16:33 435 查看
写在<head>里的js会在网页全部 载入完成后执行 而写在<body> 里的js则是 网页加载到那就执行可以运行下面的这段代码试下
<!--你运行下面的代码看看-->

<head>

<script>

alert("我是head里的js,我在网页全部载入完成后执行")

</script>

</head>

<body>

body里的js前的内容<br/>

<script>

alert("我是body里的js,网页解析到这里我就执行")

</script>

body里的js后的内容<br/>

</body>
而如果写在<body>里的话,并且 写在html上面的话  那么 因为body里的 是从上往下执行 并且 加载到哪执行到哪    就会导致 js里的 值为 null  或 undefined 因此导致方法不能用  例如下面的
<!DOCTYPE html><html><body><script>var parent=document.getElementById("div1");if(parent == null){alert("adf");//此时parent为空}var child=document.getElementById("p1");var para=document.createElement("p");var node=document.createTextNode("This is new.");para.appendChild(node);parent.replaceChild(para,child);//replaceChild 方法不能用</script><div id="div1"><p id="p1">This is a paragraph.</p><p id="p2">This is another paragraph.</p></div></body></html>
如果想让它有用 有两种方式  一种 是把js放在下面  还有一种如下所示
<!DOCTYPE html><html><body onload="load()"><script defer="defer">function load(){var parent=document.getElementById("div1");var child=document.getElementById("p1");var para=document.createElement("p");var node=document.createTextNode("This is new.");para.appendChild(node);parent.replaceChild(para,child);}</script><div id="div1"><p id="p1">This is a paragraph.</p><p id="p2">This is another paragraph.</p></div></body></html>
这样也可以用 , 不过我觉得 没这必要 还是把js写在 下面 或者写在 <head> 里吧

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: