Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest is deprecated. What to use instead?

Trying to use a pure JS approach to check if I have a valid JS image url. I am getting a warning that XMLHttpRequest is deprecated. What is a better way to do this?

urlExists(url) {
    const http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    if (http.status !== 404) {
      return true;
    }
    return false;
  }
like image 312
allencoded Avatar asked Dec 07 '16 01:12

allencoded


3 Answers

The cause of the warning was that in http.open('HEAD', url, false); you put a third argument (async) as false. As per the https://xhr.spec.whatwg.org/#synchronous-flag it should be set to true.

like image 45
bakrall Avatar answered Nov 13 '22 00:11

bakrall


You're probably getting a message that the synchronous use of XMLHttpRequest is deprecated (because of its harmful effect on the user experience; it freezes the page while waiting for a response). I can assure you that proper asynchronous use of that API is not deprecated whatsoever.

Here's some example code for the correct use:

var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
    if (this.readyState === this.DONE) {
        console.log(this.status) // do something; the request has completed
    }
}
xhr.open("HEAD", "http://example.com") // replace with URL of your choosing
xhr.send()
like image 125
gyre Avatar answered Nov 13 '22 00:11

gyre


The warning is probably because you are tyring to do a synchronous request.

like image 2
user744621 Avatar answered Nov 12 '22 23:11

user744621