浏览器在“PageUnload”和新“PageLoad”之后继续执行Javascript
作者:互联网
我们有以下AJAX throttler.这被实现为能够对一个页面执行许多(20)ajax请求而没有剩余时间超时仅仅因为前X个请求总共花费60秒.
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队列中,因此当用户尝试加载新页面时,开发人员工具会在新页面的NET区域中显示响应.我们的应用程序出于隐私原因进行了检查,不允许这种行为.这对浏览器来说是正常的,还是某种bug,或者我做错了什么?
解决方法:
一个干净的解决方案是监听window.onbeforeunload事件以中止任何尚未收到响应的ajax请求.
> https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
> Abort Ajax requests using jQuery
> jQuery: Automatically abort AjaxRequests on Page Unload?
由于以下原因,应使用beforeunload事件而不是卸载:
1)beforeunload事件比unload事件更可靠:
The exact handling of the unload event has varied from version to
version of browsers. For example, some versions of Firefox trigger the
event when a link is followed, but not when the window is closed. In
practical usage, behavior should be tested on all supported browsers,
and contrasted with the proprietary beforeunload event.
资源:
> http://api.jquery.com/unload/
> jquery: unload or 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
});
来源:
> https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
> https://developer.mozilla.org/en-US/docs/Web/Events/unload
标签:javascript,ajax,google-chrome,firefox,internet-explorer-11 来源: https://codeday.me/bug/20190623/1275379.html