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這個順序。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM