thelaumix
thelaumix

Reputation: 3

Can I detect document.readyState - like events on a completely dynamically loaded page?

I currently am building a web page that is loading its subpages with an AJAX request while using history.push for navigation. Therefore the browser will need to cache various resources before displaying them on URL change. While my code is loading the next page by AJAX (needs to be plain $.ajax, not $.load, because I not only fetch the page content but other data too) I am displaying a loading screen.

Problem: I want to display this screen as long as the browser takes for loading every single resource on the upcoming page, to prevent missing images or videos when lifting the blindfold. On the first load, I can manage this by listening for onreadystatechange or. $(document).ready() - but how can I achieve this when using dynamic loading?

Is there a way to "relisten" to the readyStateChange event or any other possibility to resolve this issue?

Best regards Lukas

Upvotes: 0

Views: 244

Answers (1)

fdomn-m
fdomn-m

Reputation: 28611

You can track each ajax request using .ajaxSend and .ajaxComplete.

When there are no more outstanding ajax requests, close your loading splash screen. If the close is in doc.ready, then it will run immediately if the doc is already ready.

var xhrCount = 0;
$(document).ajaxSend(function (e, jqXHR, options) {
    xhrCount++;
});
$(document).ajaxComplete(function (e, jqXHR, options) {
    xhrCount--;
    if (xhrCount === 0)  {
        $(function() { closeLoadingScreen(); });
    }
});

See Global Ajax Event Handlers for more info.

Upvotes: 1

Related Questions