Loader not working during synchronous ajax call in chrome

半城伤御伤魂 提交于 2019-12-05 19:08:43

I was also facing same problem from last 1 year Even with async: false. Finally got a best solution, but not sure that it will work in you case, it worked me 101%.

Below is code:-

    $.ajax({ 
                .. , 
             beforeSend: function () { showLoader(); },

             success: function (data) { hideLoader(); } 
    });


function showLoader() {
    $("#progressbar").css("display", "");
}

function hideLoader() {
    setTimeout(function () {
        $("#progressbar").css("display", "none");
    }, 1000);
}

you can make these two function common in any common javascript file. So that you can call these function multiple places or js files.

Html is :

<div class="spinnermodal" id="progressbar" style="display: none; z-index: 10001">
  <div style="position: fixed; z-index: 10001; top: 50%; left: 50%; height:65px">
      <img src="~/Images/loading.gif" alt="Loading..." />
    </div>
</div>

Css is:

.spinnermodal {
        background-color: #FFFFFF;
        height: 100%;
        left: 0;
        opacity: 0.5;
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 100000;
    }

Try this. I hope it will work for you as well. Happy coding :-)

Put setTimeout before the ajax request. I have tried many solutions but this one definitely works.

$("#loader").show();
setTimeout(function () {
  //AJAX REQUEST CODE
  $("#loader").hide();
},10);

I tried it in google-chrome it is working. May be check if you have any other error or try to post more code if you are leaving out some code on your question.

check your code on jsfiddle, it is working.

I only added this to your code:

error: function(data){
                       $('#LoaderDiv').hide(); 
               }

But notice I added the error handle function because with out it the image ( your gif ) will show forever when error happens. ( If you were getting any error response from the server then this will be a solution)

Or simply this

$.ajax({ 
                    .. , 
                 beforeSend: function () { $('#LoaderDiv').show(); },

                 success: function (data) { $('#LoaderDiv').hide(); } 
        });

which will make it little more fast

Don't use async: false, Solution is this:-

var requestStatus = 1;
$('#LoaderDiv').show();
if( requestStatus != 0) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: servicePath,
                beforeSend: function() {
                   requestStatus = 0;
                },
                success: function (data) {
                    console.log(data.d);
                    $('#LoaderDiv').hide();
                    requestStatus = 1;
                }
            });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!