Search code examples
jqueryajaxloadmask

When jQuery ajax call started, loadmask is not firing


When jQuery ajax called with async:false loadmask is not firing. Even if I call before ajax:

$("#d").on("click", function () {
    $("#d").mask("Waiting...");
    fn();
    $("#d").unmask("Waiting...");
});

Full code below:

<link href="jquery.loadmask.css" rel="stylesheet" type="text/css" />
<script src="jquery-latest.pack.js" type="text/javascript"></script>
<script src="jquery.loadmask.js" type="text/javascript"></script>

<div id="d" style="border: 1px solid red; width: 300px; height: 200px">asdfasdf</div>
<script>

    $(function () {
        $("#d").on("click", function () {
            fn();
        });
    });

    function fn() {
        var a = JSON.stringify({
            text: 'some text',
            array: [1, 2, 'three'],
            object: {
                par1: 'another text',
                par2: [3, 2, 'one'],
                par3: {}
            }
        });
        var data = {
            json: a,
            delay: 3
        }


        $.ajax({
            url: "http://jsfiddle.net/echo/json/",
            data: data,
            type: "POST",
            async: false,
            beforeSend: function (response) {
                $("#d").mask("Waiting...");
            },
            success: function (response) {
                console.log(response);
            },
            complete: function () {
                $("#d").unmask("Waiting...");
            }
        });

    }
</script>

Solution

  • it is because the browser thread is blocked by the ajax wait. a solution is to use a setTimeout().

    Try

    $("#d").on("click", function () {
        $("#d").mask("Waiting...");
        setTimeout(function(){
            fn()
            $("#d").unmask("Waiting...");
        }, 1);
    });