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

写在<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 οnlοad="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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值