就好像排隊,前面的人忙著忙著突然上廁所了,後面的人阻塞在這裡,因此我們就需要讓前面的人死到一邊去,讓後面的人跟進……AJAX就是這個概念,請求還在繼續,但我們還可以做其他事。
javascript中實現這個功能的是來自BOM的一個函數setTimeout,但相關的DOM操作也提供了一系列實現。如XMLHttpRequest對象與script標籤的onreadystatechange回調,image的onload與onerror回調,iframe的onload,DOM元素的事件回調,HTML5的跨域訊息傳送postMessage,QuickTime與flash對象的載入……
setTimeout的零秒延遲在前些年時間被國內宣揚得特別厲害,但setTimeout是所有延遲中最慢的,最少要花上10多毫秒,如果用setTimeout來開發特效,這特效會運行得比較慢。下面是一個效能測試:
<!doctype html> <html lang="en"> <head> <title>Async performance test</title> <meta charset="gb2312"> <style> pre { background-color: #eeeeee; padding: 20px; } div.test { margin: 20px; padding: 10px; border: solid black 1px; } </style> </head> <body> <div class="test"> <h3>setTimeout (slow, takes about 10 sec)</h3> <pre class="source"> function async(callback) { setTimeout(callback, 0); } </pre> <p> <input type="button" value="run" onclick="runtest(this.parentNode.parentNode)"> </p> </div> <div class="test"> <h3>img.onerror (data:uri)</h3> <pre class="source"> function async(callback) { var img = new Image; img.addEventListener('error', callback, false); img.src = 'data:,foo'; } </pre> <p> <input type="button" value="run" onclick="runtest(this.parentNode.parentNode)"> </p> </div> <div class="test"> <h3>script.onreadystatechange</h3> <pre class="source"> function async(callback) { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "javascript:"; script.onreadystatechange = function () { document.body.removeChild(script); callback(); } document.body.appendChild(script); } </pre> <p> <input type="button" value="run" onclick="runtest(this.parentNode.parentNode)"> </p> </div> <div class="test"> <h3>script.onload (data:uri)</h3> <pre class="source"> function async(callback) { var script = document.createElement('script'); script.onload = function() { document.body.removeChild(script); callback(); } script.src = 'data:text/javascript,'; document.body.appendChild(script); } </pre> <p> <input type="button" value="run" onclick="runtest(this.parentNode.parentNode)"> </p> </div> <div class="test"> <h3>xhr.onreadystatechange (data:text/plain,foo)</h3> <pre class="source"> function async(callback) { var xhr = new XMLHttpRequest; xhr.open('GET','data:text/plain,foo',true); xhr.onreadystatechange = function() { xhr.onreadystatechange = null; callback(); }; xhr.send(null); } </pre> <p> <input type="button" value="run" onclick="runtest(this.parentNode.parentNode)"> </p> </div> <div class="test"> <h3>self.postMessage</h3> <pre class="source"> function async(callback) { var n = ++async.count; window.addEventListener('message',function(e){ if (e.data == n) { window.removeEventListener('message', arguments.callee,false); callback(); } },false); window.postMessage(n, location.protocol + "//" + location.host); } async.count = 0; </pre> <p> <input type="button" value="run" onclick="runtest(this.parentNode.parentNode)"> </p> </div> <script> function runtest(div) { var pre = div.getElementsByTagName('pre')[0]; eval(pre.textContent || pre.innerText); // load async function var p = div.getElementsByTagName('p')[0]; var t = new Date, n = 1000, i = 0, flag = true; try { test(); } catch (e) {} setTimeout(function() {if (flag) p.innerHTML = 'failed'; flag = false}, 200); function test() { if (i++ < n) { async(test); if (flag && i == 2) { p.innerHTML = 'running'; flag = false; } } else { p.innerHTML = "Average delay was " + (new Date - t)/n + "ms, over " + n + " iterations."; } } } </script> </body> </html>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]
|
Chromium |
Safari |
Firefox |
Opera 10.10 |
Opera 10.50 |
| setTimeout |
4.32ms |
10.201ms |
10.302ms |
10.38ms |
9.876ms |
| img.onerror |
0.199ms |
0.678ms |
0.201ms |
0.058ms |
0.575ms |
| script.onreadystatechange |
fail |
fail |
fail |
fail |
fail |
| script.onload |
0.414ms |
0.138ms |
0.414ms |
fail |
fail |
| xhr.onreadystatechange |
fail |
0.622ms |
fail |
0.078ms |
0.079ms |
| self.postMessage |
0.096ms |
0.123ms |
0.112ms |
0.049ms |
0.094ms |
為了處理這種非同步呼叫,Mochikit從Python的Twisted架構借來了Deferred這個類,並用它來處理AJAX的回調。AJAX的回調通常有兩種,成功載入時的回調與請求失敗的回調,IE8的XDomainRequest就有這兩種回調了,標準瀏覽器的script與image也有這兩種回調,分別稱之為onload與onerror。Mochikit的Deferred執行個體就內建一個數組,每次包含這兩種回調,依次執行。Mochikit這偉大的遺產後來由dojo發揚光大了,至於怎麼用,自己google吧。
下面是我的架構對它的應用,我已把它整合到我的架構中:
複製代碼 代碼如下:
<!doctype html>
<html>
<head>
<title>非同步作業例子 by 司徒正美</title>
<meta charset="utf-8"/>
<meta content="IE=8" http-equiv="X-UA-Compatible"/>
<meta name="keywords" content="非同步作業例子 by 司徒正美" />
<meta name="description" content="非同步作業例子 by 司徒正美" />
<%= javascript_include_tag "dom.js" %>
<%= javascript_tag "window._token = '#{form_authenticity_token}'" if ActionController::Base.allow_forgery_protection %>
<script type="text/javascript" charset="utf-8">
dom.ready(function(){
dom.require("ajax");
dom.ajax({method:"post",
async:true,
dataType:"text",
data:{authenticity_token:window._token}
}).next(function(a){
alert(a)
});
dom.jsonp({url:"http://del.icio.us/feeds/json/fans/stomita"}).next(function(json){
alert(json)
}).error(function(e){
alert(e)
});
});
</script>
</head>
<body>
</body>
</html>
後台:
複製代碼 代碼如下:
class HomeController < ApplicationController
def index
if request.xhr?
name = params[:name]
puts "-------------"
render :text => "<p>The time is <b>" + DateTime.now.to_s + "</b></p>"
end
end
end
在日本一部落格提到這樣一個捕捉非同步錯誤的例子:
複製代碼 代碼如下:
function throwError(){
throw new Error('ERROR');
}
try{
setTimeout(throwError, 3000);
} catch(e){
alert(e);
}
看來try...catch是無法捕捉這種形式的錯誤,window.onerror可以,但好像只有IE與FF支援。如果用Deferred來處理,就簡單了!
複製代碼 代碼如下:
dom.Deferred.next(function () {
throw new Error("錯誤")
}).wait(1).error(function(e){
alert(e instanceof Error)
});
列隊處理。由於是使用了非同步,因此不會阻塞頁面的演染。
複製代碼 代碼如下:
<!doctype html>
<html>
<head>
<title>非同步作業例子 by 司徒正美</title>
<meta charset="utf-8"/>
<meta content="IE=8" http-equiv="X-UA-Compatible"/>
<meta name="keywords" content="非同步作業例子 by 司徒正美" />
<meta name="description" content="非同步作業例子 by 司徒正美" />
<%= javascript_include_tag "dom.js" %>
<script type="text/javascript" charset="utf-8">
dom.require("deferred");
dom.require("query");
dom.ready(function(){
var a = dom("#aaa")[0];
dom.Deferred.loop(10,function(i){
a.innerHTML += i+"<br/>"
});
dom.Deferred.loop(10,function(i){
a.innerHTML += String.fromCharCode(i+97)+"<br/>"
});
dom.Deferred.loop(10,function(i){
a.innerHTML += "司徒正美"+i+"<br/>"
});
});
/*結果
0
a
司徒正美0
1
司徒正美1
2
c
司徒正美2
3
d
司徒正美3
4
e
司徒正美4
5
f
司徒正美5
6
g
司徒正美6
7
h
司徒正美7
8
i
司徒正美8
9
j
司徒正美9
*/
</script>
</head>
<body>
<div id="aaa"></div>
</body>
</html>