js放在<head>里 和 <body>里的区别

来源:互联网 发布:免费硬盘数据恢复软件 编辑:程序博客网 时间:2024/06/09 19:49

写在<head>里的js会在网页全部 在载入前执行  所以如果head里只能写 鼠标事件   调用的  方法  写在里面            而写在<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> 里吧

                                             
0 0
原创粉丝点击