寫在前面:本文中全部測試實例皆基於mac版chrome, firefox及safari。chrome
同步請求,其實也就是告訴js引擎:你先把我這個處理了再作別的事情!因此同步無需等,在send()以後直接往responseText中拿數據就好。json
function req() { var xhr = new XMLHttpRequest(); xhr.open('get', './data.json',false); xhr.send(); console.log(xhr.responseText);}req();
注:在同步請求時,各瀏覽器都會提示同步方法已不建議使用,由於它會影響主線程。原話是:Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.瀏覽器
異步請求就是自身(XMLHttpRequest對象)綁定個事件先,告訴js引擎說:我這兒有個請求哈,老兄有空幫我處理下,完了幫我把回調也處理下。異步
function req() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function (e) { if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); } } xhr.open('get', './data.json'); xhr.send();}
前段時間由於XMLHttpRequest對象找到MDN看,其中裏面有提示開發者,若是用了同步請求,那麼不要用onreadystatechange作綁定了,這很明白,你都同步了,就無需再綁定了嘛。我誤操做(手賤),額....async
function req() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function (e) { //console.log(xhr.readyState); if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); } } xhr.open('get', './data.json',false); xhr.send(); console.log(xhr.responseText);}
結果還真輸出來告終果....這是個什麼狀況?引擎依然沒有忘記去查下回調。。。
去掉line4的註釋,發現有兩個狀態被打印出來,分別是1(send()方法還未被調用)和4(請求結束).
去掉line11的註釋,證明其執行順序爲請求-回調-同步操做(即這裏的line11).post
查看MDN時有這麼一句話: If the request is asynchronous (which is the default), this method returns as soon as the request is sent. If the request is synchronous, this method doesn't return until the response has arrived.
也就是說,send調用後,若是請求是異步的,它會在調用後立刻返回;若是請求是同步的,那麼它會等到請求完成後再返回。這也就解釋了上面的同步請求中爲何只有1和4兩個狀態了。
囉嗦了這麼多,純屬沒事瞎bb,一句話,儘可能少用同步,用同步別用事件綁定。測試
原腳本改成:this
var w=new Worker('./worker.js');w.onmessage=function(e){ console.log(e.data);}
新建腳本文件worker.jsspa
function req() { var xhr = new XMLHttpRequest(); xhr.open('get', './data.json',false); xhr.send(); postMessage(xhr.responseText);}req();
此時瀏覽器便再也不提示上面說的Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.了。firefox