syed imty
syed imty

Reputation: 1028

Wierd delay in retrieving dom element

I have created a loading screen plugin. The scenario is that i am doing page navigation using ajax loading. So before loading a page using ajax, i would show an loading screen using the code $('body).loadingMask('show') and once the page is loaded completely loaded, i would remove the loading screen using the code $('body').loadingMask('hide).

The problem is that, there is some delay in retrieving the target dom element inside the plugin.

This is the general structure of the code

$('body').loadingMask('show');
$.ajax({
url : 'views/next.html',
    async : false,
success : function(content, textStatus, jqXHR) {
$('body').append(content);
},
error : function(content, textStatus, jqXHR) {
throw "Unable to load template. Please check the path and name of the template"
}
});
$('body').loadingMask('hide');

The problem is that , inside the show function of the loadingMask plugin, There is a delay in retrieving the target dom element(i.e body) . So pratically, the code $('body).loadingMask('show') runs only after the ajax page is finished loading.

In order to make it work , i have added a time delay. Which seems to work fine.

This is the modified code

$('body').loadingMask('show');
setTimeout(function(){
$.ajax({
url : 'views/next.html',
    async : false,
success : function(content, textStatus, jqXHR) {
$('body').append(content);
},
error : function(content, textStatus, jqXHR) {
throw "Unable to load template. Please check the path and name of the template"
}
});
},500);
$('body').loadingMask('hide');

Now i can see the loading screen, while the page loads.

Upvotes: 0

Views: 90

Answers (1)

charlietfl
charlietfl

Reputation: 171690

If you remove async:false you can call your plugin withing the ajax success, right after the content gets added.

async:false is deprecated and often leads to unforeseen problems

$('body').loadingMask('show');
$.ajax({
    url: 'views/next.html',
    success: function(content, textStatus, jqXHR) {
        $('body').append(content).loadingMask('hide');
    },
    error: function(content, textStatus, jqXHR) {
           /* likely need to remove maske here and add something to content to advise user*/
        throw "Unable to load template. Please check the path and name of the template"
    }
});

Upvotes: 1

Related Questions