欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-12 13:33:40
1.今天写js碰到一个奇怪的问题,写好的js放到body里面执行,但是放到head中没有任何效果,为什么导致这种原因呢? 看失效代码:

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

看失效代码:

<!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;background-color:#4e74a5;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中。

<!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;background-color:#4e74a5;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这个顺序。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!

上一篇:

下一篇: