jQuery: Automatically abort AjaxRequests on Page Unload?

后端 未结 5 1604
有刺的猬
有刺的猬 2020-12-06 05:48

Thanks for reading.

I\'ve noticed that if I have a page that has one or more ajax requests open, and I click a link to leave a page, or refresh it, it will wait for

5条回答
  •  独厮守ぢ
    2020-12-06 06:22

    The following code is tested and aborts all outstanding jQuery ajax requests on page unload in Chrome, but it gets used by Edge and IE using clients as well without error.

    Put the following as the first jQuery ready handler:

    $(onPageLoaded)
    

    And put this somewhere accessible:

    function onPageLoaded() {
        var jqxhrs = [];
    
        $(window).bind("beforeunload", function (event) {
            $.each(jqxhrs, function (idx, jqxhr) {
                if (jqxhr)
                    jqxhr.abort();
            });
        });
    
        function registerJqxhr(event, jqxhr, settings) {
            jqxhrs.push(jqxhr);
        }
    
        function unregisterJqxhr(event, jqxhr, settings) {
            var idx = $.inArray(jqxhr, jqxhrs);
            jqxhrs.splice(idx, 1);
        }
    
        $(document).ajaxSend(registerJqxhr);
        $(document).ajaxComplete(unregisterJqxhr);
    };
    

提交回复
热议问题