Check Pending AJAX requests or HTTP GET/POST request
How do i check if the page has pending AJAX or HTTP GET/POST requests? I use javascript and/or python for this checking.
what i wanted to do is execute a script if a page has finished all requests. onload doesn't work for me, if you used firebugs net panel, you would know. onload fires when the page is loaded but there is a possibility that there开发者_如何学运维 are still pending request hanging around somewhere.
thank you in advance.
figured it out. thanks for the effort guys. just plain and simple javascript.
interValRef = 0;
interValRef = setInterval("checkState();",100)
function checkState(){
if(document.readyState == 'complete'){
clearInterval(interValRef);
myFunc();
}
}
Here is the best way of checking it.
var loadingDone = document.readyState=="complete" && jQuery.active === 0;
So loadingDone will be true, if Ajax calls are done. If its false then you can add waiting.
I see you mention you are using Prototype.js. You can track active requests with Prototype by checking the Ajax.activeRequestCount
value. You could check this using setTimeout or setInterval to make sure that any requests triggered on page load have completed (if that's what you're looking to do)
Assuming you are using prototype.js you could keep track with a counter of all your request objects
var ACTIVE_REQUESTS = 0; // GLOBAL
ACTIVE_REQUESTS++
new Ajax.Request('/your/url', {
onSuccess: function(response) {
ACTIVE_REQUESTS--;
// Handle the response content...
}
}));
console.log("there are " + ACTIVE_REQUESTS + " open AJAX requests pending");
You would need to keep track of each XMLHttpRequest and monitor whether it completes or the asynchronous callback is executed.
I think you want to know if the HTML is fully loaded. In this case you can use the dom:loaded event. Here is an example on how to use it with prototype (but there must be a variant for other JS frameworks):
document.observe("dom:loaded", function() {
// do whatever you want to do
});
This event will fire as soon as the DOM tree is loaded. So even before all the images or external data (including iframe) are loaded.
I can confirm that document.readyState can still be 'complete' even if there are pending requests in network tab.
The code I developed for now to check if the page has been loaded completely or not is:
var prevSize= document.body.innerHTML.length;
var id= setInterval(()=>{
let currSize=document.body.innerHTML.length;
if(prevSize===currSize){
clearInterval(id);
console.log("page loaded successfully");
}
else{
console.log("loading...");
prevSize=currSize;
}
}, 3000)
This checks document.body.innerHTML length in every 3s. Not a best solution, but atleast it works.
document.addEventListener("readystatechange", function(event) {
if (document.readyState === "complete") {
console.log("complete");
}
});
精彩评论