js放到head中失效的原因与解决方法

1.今天写js碰到一个奇怪的问题,写好的js放到body里面执行,但是放到head中没有任何效果,为什么导致这种原因呢?

看失效代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
< html xmlns = "http://www.w3.org/1999/xhtml" >
  < head >
  < title > new document </ title >
  < meta http-equiv = "Content-Type" content = "text/html;charset=UTF-8" />
  < style type = "text/css" >
  .login{width:40px;height:25px;line-height:25px;margin-top:30px;text-align:center;color:#FFF;}
  </ style >
  < script type = "text/javascript" src = "jquery-1.7.1.min.js" ></ script >
  < script type = "text/javascript" >
  $(".login").click(function(){
    alert(1);
    });
  </ script >
  </ head >
  < body >
  < input type = "text" class = "pass" />
  < div id = "enter" class = "login" > 登录</ div >
  </ body >
</ html >

2.解决办法:把js代码放到body中,或者利用 window.onload = function(){} 代码包裹,文档加载之后再执行,以后不建议放到head中。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
< html xmlns = "http://www.w3.org/1999/xhtml" >
  < head >
  < title > new document </ title >
  < meta http-equiv = "Content-Type" content = "text/html;charset=UTF-8" />
  < style type = "text/css" >
  .login{width:40px;height:25px;line-height:25px;margin-top:30px;text-align:center;color:#FFF;}
  </ style >
  < script type = "text/javascript" src = "jquery-1.7.1.min.js" ></ script >
  < script type = "text/javascript" >
  window.onload = function(){
  $(".login").click(function(){
    alert(1);
    });
  }
  </ script >
  </ head >
  < body >
  < input type = "text" class = "pass" />
  < div id = "enter" class = "login" > 登录</ div >
  </ body >
</ html >

3.原因:

因为文档还没加载,就读了js,js就不起作用了想在head里用的话,用window.onload = function(){//这里包裹你的代码}

js可以分为外部的和内部的,外部的js一般放到head内。内部的js也叫本页面的JS脚本,内部的js一般放到body内,这样做的目的有很多:

1.不阻塞页面的加载(事实上js会被缓存)。

2.可以直接在js里操作dom,这时候dom是准备好的,即保证js运行时dom是存在的。

3.建议的方式是放在页面底部,监听window.onload 或 readystate 来触发js。

4.延伸:

head内的js会阻塞页面的传输和页面的渲染。head 内的 JavaScript 需要执行结束才开始渲染 body,所以尽量不要将 JS 文件放在 head 内。可以选择在 document 完成时,或者特定区块后引入和执行 JavaScript。head 内的 JavaScript 需要执行结束才开始渲染 body,所以尽量不要将 JS 文件放在 head 内。可以选择在 document 完成时,或者特定区块后引入和执行 JavaScript。

所以在head内的js一般要先执行完后,才开始渲染body页面。为了避免head引入的js脚本阻塞流浪器中主解析引擎对dom的解析工作,对dom的渲染,一般原则是,样式在前面,dom文档,脚本在最后面。遵循先解析再渲染再执行script这个顺序。

转载于:https://www.cnblogs.com/daochong/p/7428354.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值