DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> JavaScript的事件綁定(方便不支持js的時候)
JavaScript的事件綁定(方便不支持js的時候)
編輯:關於JavaScript     

首先,比如我們使用JavaScript來加強我們的網頁,但是我們要考慮到,如果用戶的浏覽器不支持JavaScript,或者用戶disable了JavaScript的功能,那我們的網頁能不能正常顯示呢?例如下面的例子,

復制代碼 代碼如下:<a href = "#" onclick = "popUp('http://www.jb51.net') ; return false;">

其中popUp這個函數是自定義的,新打開一個窗口來限制URL中的網頁。但是如果當客戶端不支持時,那這個網頁就不能正常工作了。所以我們在這樣做的使用,也考慮到更多,使用如下的代碼就會顯得更加合適。

復制代碼 代碼如下:
<a href = "http://www.jb51.net" onclick = "popUp(this.href) ; return false;"> 

接著,作者以CSS為例子。在我們使用CSS的過程中,我們發現,除了我們使用了<link>把CSS文件給加載進來外,我們沒有在我們的網頁內容中加入任何css相關的代碼,這樣就能很好的把structure和style分開了,即我們的css的代碼沒有侵入我們的主要代碼裡面。這樣就算客戶端不知道css,但是我們的主要內容客戶還是可以看到的,我們的內容結構也能在客戶那裡顯示出來。所以JavaScript相當於behavior層,css相當於presentation層。JavaScript也能像CSS一樣做到沒有侵入性。下面是書上的一個例子。

復制代碼 代碼如下:
<a href = "http://www.jb51.net" onclick = "popUp(this.href) ; return false;">

上面這段代碼已經能保證在客戶端不支持JavaScript的情況下仍然可以正常的工作,但是上面的代碼中出現了onclick這樣的event handler。所以現在我們使用像CSS中的方式來完成我們所要的功能。如下:

復制代碼 代碼如下:
<a href = "http://www.jb51.net" class = "popup">

這樣,我們能在這個頁面加載完成的時候,執行window.onload中,來檢測哪些<a>是使用了class,然後統一使用popUp的方法。如下代碼

復制代碼 代碼如下:
var links = document.getElementsByTagName("a");
for (var i=0 ; i<links.length ; i++) {
 if (links[i].getAttribute("class") == "popup") {
  links[i].onclick = function() {
   popUp(this.getAttribute("href"));  //Attention use this in  this place. Because this is equals onClick = "popUp(this.href)"
   //so we cann't use links[i].
   return false;
  }
 }
}

這樣就能更少地侵入我們html代碼了。

  最後,作者講了我們要做到向後兼容和JavaScript的最小化。向後兼容,我們可以使用類似if(document.getElementById)來測試這個方法時候存在,存在了才能使用。JavaScript代碼的最小化主要是為了減少JavaScript,這樣能加快我們網頁的加載。

  下面我在看書的時候碰到不懂的問題,希望大蝦們能幫忙解決一下。

   對於<script>應該放在哪裡?JavaScript DOM編程藝術中所說的,我們可以把<script>放在</body>之前,不要放在<head></head>裡,這樣可以加快我們加載page的速度。不是很理解。

  

原文:

The placement of your scripts in the markup also plays a big part in initial load times. Traditionally,
we were told to always place scripts in the <head> portion of the document, but there's a problem with
that. Scripts in the <head> block the browser's ability to download additional files (such as images or
other scripts) in parallel. In general, the HTTP specification suggests that browsers download no more
than two items at the same time per hostname. While a script is downloading, however, the browser
won't start any other downloads, even on different hostnames, so everything must wait until the script
has finished.
If you're following the progressive enhancement and unobtrusive methodologies discussed earlier
in the chapter, then moving your <script> tags shouldn't be an issue. You can make your pages load
faster simply by including all your <script> tags at the end of the document, directly before the </body>

tag. When the scripts load, your window load events will still apply your changes to the document.

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved