Popo
Popo

Reputation: 2460

Spinner bound to ajax call will not display unless I put an alert in the javascript

I wrote a simple method that adds a spinner to the main body of an html page and binds the event to an ajaxstart method then removes it on the ajaxstop.

StartAjaxCallSpinner = function (spinnerObj) {    
    var $bod = $("Body");
    if ($('#bgSpinnerDiv')[0] == undefined && $('#spinnerHolder')[0] == undefined) {
        $bod.append("<div id='spinnerHolder' style='display:none;'></div><div id='bgSpinnerDiv'></div>");
    }

    $('#spinnerHolder')
            .hide()  
            .ajaxStart(function () {
                $('#bgSpinnerDiv').css({ 'background-color': 'black',
                    'height': '100%',
                    'left': '0px',
                    'opacity': '0.7',
                    'position': 'fixed',
                    'top': '0px',
                    'width': '100%',
                    'z-index': '1000001'
                });
                $(this).css({ 'position': 'fixed',
                    'top': '50%',
                    'left': '50%',
                    'width': '130px',
                    'height': '130px',
                    'margin-top': '-65px',
                    'margin-left': '-65px',
                    'z-index': '1000002',
                    'display': 'block',
                    'border': '1px solid black',
                    'border-radius': '5px',
                    'background': " white url('" + spinnerObj.SpinnerUri + "') no-repeat center center"
                });
                $(this).show();
                //alert('test');
            })
            .ajaxStop(function () {
                $(this).hide();
                $('#bgSpinnerDiv').removeAttr("style").unbind('ajaxStart', UnBindAjaxStop($('#bgSpinnerDiv')));
                $(this).removeAttr("style").unbind('ajaxStart', UnBindAjaxStop(this));
            });
};

UnBindAjaxStop = function (me) {
    $(me).unbind('ajaxStop');
};

I call the method before an ajax call and pass it an object with the uri of the spinner gif, but the spinner and background do not display unless I have an alert. I have tried adding a setTimeout()function{/*do some code*/},1000) in various places, but that did not seems to help.

I saw a similar issue in this posting but the setTimeout does not seems to help. Any ideas?

Upvotes: 3

Views: 1313

Answers (1)

Kevin B
Kevin B

Reputation: 95058

If your ajax request is being sent synchronously, the browser will be locked up immediately before it has time to render the spinner. When it's done, it will immediately hide the spinner, thus causing it to not display at all. The alert gave the browser enough time to render the spinner before sending the ajax request.

Remove async: false

Upvotes: 6

Related Questions