I am making a simple page to display all the images that use chromecast as a slideshow. I have found a JSON file on github with the links to the images. The problem is that some of them are no longer on the server (they return 404), so my idea is that before loading them, request only the header (fetchHead function) so as not to load the body of the image, if it returns a 404, no I include it, but it seems that when the if is correct (it returns true because the header status is 200), it always returns false, so the image is never loaded.
I'm going to leave the code, but it seems to me that the problem is in the scope of the return...
probe = (a) => {
for (i = 0; i < 10; i++) {
if (fetchHead(a[i].url)) {
console.log("done");
} else {
console.log("err");
}
}
};
fetchHead = (a) => {
let head = new XMLHttpRequest();
head.onreadystatechange = function() {
if (this.readystate === 2) {
if (this.status === 200) {
return true;
} else {
return false;
}
}
};
head.open('HEAD', a);
head.send();
};
Needless to say, the a parameter is the JSON object from github
I explain myself fatally, but I think that with the code it can be clear...
I clarify, in the for there is a 10 so as not to overload the server with calls, keep in mind that each complete load of this page is about 120MB of images.
answering the question
It never returns 200 because the property
readystate
is misspelled, it'sreadyState
with a capital S.There are two ways to make requests: asynchronous and synchronous.
Do the next:
It implies that they are synchronous requests, however that would take more time since they must be made one by one and wait for their result. In addition, the HTTP request is being made asynchronously, that is, there is a mix of intentions in the code.
asynchronous form
To make it work optimally, making asynchronous requests, a couple of changes were made to the original code.
fetchHead()
. Instead, just the array of urls is iterated and the function is calledfetchHead()
for each one so that all urls are processed simultaneously.callback()
that will be called when all the urls have been processed, withincallback()
it you can filter the urls that work and use them as desired.synchronous form
For this, the function was modified
fetchHead()
so that it makes the requests synchronously, the code is simpler but less efficient.