13

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;
  }
Tavish Aggarwal
  • 1,020
  • 3
  • 22
  • 51
allencoded
  • 7,015
  • 17
  • 72
  • 126
  • What environment/browser are you getting the warning in? – Chris Tavares Dec 07 '16 at 01:50
  • 2
    Read the complete warning you got – Dekel Dec 07 '16 at 01:52
  • 3
    Possible duplicate of [Alternatives for Javascript Synchronous XMLHttpRequest (as timing out in Safari)](http://stackoverflow.com/questions/10076614/alternatives-for-javascript-synchronous-xmlhttprequest-as-timing-out-in-safari) – Sebastian Simon Dec 07 '16 at 01:57
  • This is the simplest usage of asynchronous XMLHttpRequest. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests – bodomalo Sep 04 '19 at 06:43

3 Answers3

15

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()
gyre
  • 16,369
  • 3
  • 37
  • 47
3

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.

bakrall
  • 465
  • 7
  • 21
2

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

user744621
  • 147
  • 2
  • 8