Recreating jQuery's ajaxStart and ajaxComplete functionality

后端 未结 1 1680
你的背包
你的背包 2020-12-06 14:25

I\'m trying to reproduce jQuery\'s functions ajaxComplete and ajaxStart without jQuery so that they could be used in any environment with no library dependencies (it\'s a sp

相关标签:
1条回答
  • 2020-12-06 14:54

    Using .onreadystatechange wasn't working because I was testing with jQuery and jQuery's ajax methods manipulate and removes the onreadystatechange property.

    However, adding an event listener for loadend works just fine everywhere but IE. For IE, I set up an interval instead - not the optimal solution, but it works for my needs. I only intended this script to work on IE8+ and modern browsers.

    XMLHttpRequest.prototype.send = (function(orig){
        return function(){
            _core._fireAjaxEvents('pre', this._HREF);
    
            if (!/MSIE/.test(navigator.userAgent)){
                this.addEventListener("loadend", function(){
                    _core._fireAjaxEvents('post', this._HREF);
                }, false);
            } else {
                var xhr = this,
                waiter = setInterval(function(){
                    if(xhr.readyState && xhr.readyState == 4){
                        _core._fireAjaxEvents('post', xhr._HREF);
                        clearInterval(waiter);
                    }
                }, 50);
            }
    
            return orig.apply(this, arguments);
        };
    })(XMLHttpRequest.prototype.send);
    
    0 讨论(0)
提交回复
热议问题