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"> <head> <title> new document </title> <metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"/> <styletype="text/css"> .login{width:40px;height:25px;line-height:25px;margin-top:30px;text-align:center;color:#FFF;} </style> <scripttype="text/javascript"src="jquery-1.7.1.min.js"></script> <scripttype="text/javascript"> $(".login").click(function(){   alert(1);   }); </script> </head> <body> <inputtype="text"class="pass"/> <divid="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"> <head> <title> new document </title> <metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"/> <styletype="text/css"> .login{width:40px;height:25px;line-height:25px;margin-top:30px;text-align:center;color:#FFF;} </style> <scripttype="text/javascript"src="jquery-1.7.1.min.js"></script> <scripttype="text/javascript"> window.onload = function(){ $(".login").click(function(){   alert(1);   }); }  </script> </head> <body> <inputtype="text"class="pass"/> <divid="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这个顺序。
 
                    
                 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号