检查浏览器的XHR和progress-event功能

Check browsers capability of XHR and progress-event

本文关键字:progress-event 功能 XHR 浏览器 检查      更新时间:2023-09-26

下面这个问题:

jQuery AJAX上传大文本字段的进度

如何使其与旧浏览器兼容?

正如您在上面的问题中看到的,我依赖于XHR和进度事件。现在,对于较旧的浏览器,我需要检测它们是否不具备这些功能之一,以便我可以跳过进度条并仍然制作AJAX-post。

我认为它可以这样工作:

$.ajax({
        xhr: function() {
            var xhr = $.ajaxSettings.xhr();
            if (xhr instanceof window.XMLHttpRequest) {
                xhr.addEventListener('progress', function(event) {
                    if (event.lengthComputable) {
                        progressPercent = Math.round(event.loaded/event.total*100)+'%';
                        $loader.width(progressPercent);
                    }
                }, false);
            }else{
                alert('XHR is no instance of window.XMLHttpRequest');
            }
            return xhr;
        },
        type: "POST",
...

但是我不知道这是保存还是还有什么需要检查的

谢谢!

对于接近完全安全的情况,您可以使用try/catch/finally结构:

$.ajax({
    xhr: function() {
        var xhr = $.ajaxSettings.xhr();
        try {
            xhr.addEventListener('progress', function(event) {
                if (event.lengthComputable) {
                    $loader.width(Math.round(event.loaded / event.total * 100) + '%');
                }
            }, false);
        }
        catch(err) {
            //Progess not available
            //Take appropriate action - eg hide the progress thermometer
            $loader.hide();
        }
        finally {
            return xhr;
        }
    },
    type: "POST",
    ...
}):