Kyle
Kyle

Reputation: 61

Determine through javascript if another URL exists

I am working with a servlet which serves up an image. However, it takes about 30 seconds for this to be generated. When complete, it appears on an OpenLayers interactive map.

I am trying to figure out a way for the user, who is at www.test.com to get confirmation the image is being processed or is complete, which is located at www.test2.com. If I open test2.com, I can see that the page is trying to load. When complete, the image also appears on my map on test.com.

However, I can't figure out how to test if this image exists or not. I am looking for something probably like

    if(image exists at http://test2.com) {alert("request is done");

or possibly

    if(http://test2.com is loading) {doing something);

I just don't want the user sitting by if the request fails. If it fails, the url will complete its load - however, no image will appear. Any guidance will be very appreciated! Thanks!

Kyle

Upvotes: 0

Views: 748

Answers (2)

epascarello
epascarello

Reputation: 207511

If it is a different server, JavaScript will not be able to make any type of Ajax request to that server to see if it exists. You would have to have a proxy on the local domain which could make a head request to the second domain.

If you are waiting until the image is loaded to work with it, you can always do an image preloader, but that will take the full time for the image to render before the onload event fires.

var img = new Image();
img.src = theUrl;
img.onload = function() {
    nextStep(this);
};
img.onerror = function() {
     imgLoadingError(this);
};

Upvotes: 3

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

IF you have control over the other server, you could put a small image on that server and do something like this: (Untested code, typed in directly)

var img = new Image();
// Note the order of these two statements
img.onload = function()("The image loaded! Server must be up");
img.src = "http://example2.com/myflag.png";

Upvotes: 0

Related Questions