简体   繁体   中英

Why does this jQuery synchronous ajax call block the UI before it has executed?

I'm confused by this synchronous jquery ajax request. The ajax loader doesn't show until after the ajax call is complete. I'm well aware that the synchronous request will block the UI, but why does it start blocking before that line of code has been hit? I must be misunderstanding something fundamental about execution order.

            $("#ajax-loader").show(1, function(){
                $.ajax({
                    url: xxx,
                    type: "POST",
                    async: false,
                    success: function (data) {
                        hideAjaxLoader();
                    }
                });
            });

Even though jQuery believes the animation is complete when it calls your code containing the synchronous ajax call, that doesn't mean the browser has done all of its work to render the result before that callback. And since most browsers completely block their UI during a synchronous ajax call, it doesn't get around to it until later.

Obviously, wherever possible, just don't use synchronous ajax, since it has this behavior of blocking the UI.

But , if you absolutely cannot avoid making it synchronous (I've never encountered a valid example of such a situation; I'm told they exist), add a brief delay after jQuery thinks the animation is done before starting your ajax. Firefox in particular seems to want a fair bit of time:

$("#ajax-loader").show(1, function(){
    setTimeout(function() {
        $.ajax({
            url: xxx,
            type: "POST",
            async: false,
            success: function (data) {
                hideAjaxLoader();
            }
        });
    }, 50); // 50 ms
});

Again , I strongly recommend not using synchronous ajax, but if you need to, just delay the onset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM