2015-02-24 68 views
4

我們有以下的AJAX調速器。這被實現爲能夠對一個頁面執行許多(20+)ajax請求,而不會因爲第一個X請求總共需要60秒而超時。瀏覽器在「PageUnload」和新的「PageLoad」後繼續執行Javascript

RequestThrottler: { 
    maximumConcurrentRequests: 3, //default to 3   
    requestQueue: new Array(), 
    numberOfRequestCurrentlyProcessing: 0, 

    addRequestToQueue: function (currentRequest) { 
     var self = this; 
     self.requestQueue.push(currentRequest); 

     if (self.numberOfRequestCurrentlyProcessing < self.maximumConcurrentRequests) { self.sendNextRequest(); } 
    }, 

    sendNextRequest: function() { 
     var self = this; 
     if (self.numberOfRequestCurrentlyProcessing >= self.maximumConcurrentRequests) { return; } 
     if (self.requestQueue.length === 0) { return; } 

     var currentRequest = self.requestQueue.pop(); 
     self.numberOfRequestCurrentlyProcessing++; 
     AJAX.SendAjaxRequest(currentRequest.url, currentRequest.httpMethod, 
      function(data){ 
       self.numberOfRequestCurrentlyProcessing--; 
       currentRequest.onSuccessCallback(data); 
       self.sendNextRequest(); 
      }, 
      function(){ 
       self.numberOfRequestCurrentlyProcessing--; 
       currentRequest.onErrorCallback(); 
       self.sendNextRequest(); 
      }); 
    }, 

    sendUpdateRequest: function (currentRequest) { 
     var self = this; 
     self.addRequestToQueue(currentRequest); 
    } 
} 

然而,因爲這些請求都坐在一個Javascript隊列中,當用戶嘗試加載一個新的頁面,開發者工具顯示在新頁面的淨面積的響應。我們的應用程序爲隱私原因進行了檢查,以防止這種行爲。這對瀏覽器來說是正常的,還是某種錯誤,或者我做錯了什麼?

回答

4

一個乾淨的解決方案是收聽window.onbeforeunload事件到abort任何尚未收到響應的ajax請求。

beforeunload事件,應使用而不是unload,原因如下:

1)beforeunload事件比unload事件更可靠:

卸載事件的確切處理從版本到 版本的瀏覽器有所不同。例如,某些版本的Firefox在遵循鏈接時會觸發 事件,但當窗口關閉時不會觸發該事件。在 的實際用法中,應在所有支持的瀏覽器上測試行爲, 並與專有的beforeunload事件進行對比。

源:

2)beforeunload事件可以取消而unload事件不能被取消。如果您希望在發生beforeunload事件時提示用戶,這將爲您提供靈活性。確認將詢問用戶是否希望繼續導航到其他頁面,或者如果他們想取消,因爲並非所有ajax請求都已完成。

window.addEventListener("beforeunload", function (e) { 
    var confirmationMessage = "\o/"; 

    (e || window.event).returnValue = confirmationMessage;  // Gecko and Trident 
    return confirmationMessage;        // Gecko and WebKit 
}); 

來源:

+2

爲什麼你選擇的onbeforeunload而不是onunload的? – theB3RV 2015-03-03 13:26:13

+0

更新地址推理的答案 – peterdotjs 2015-03-03 17:06:43

+0

我應該注意到,我有另一個綁定到before unload事件的函數,並且注意到它在其他事件發生時觸發(例如文件下載和flash播放器啓動)。在這種情況下,我不希望我的ajax請求退出。 – theB3RV 2015-03-03 20:12:17

相關問題