0

Is it possible in JavaScript to have a loop that checks to see whether an image is available and then if it is, change the SRC of an img tag to match? The loop would have a counter so the first time it is run it would look for image1.png and the image2.png and so on.

I want it to load image1.png once it is avaliable, and then check to see if image2.png is avaliable, and as soon as it is, load it into the page, and then do the same with image3.png and so on.

I have tried using

function imageExists(image_url){

  var http = new XMLHttpRequest();

  http.open('HEAD', image_url, false);
  http.send();

  return http.status != 404;

}

from Check if image exists on server using JavaScript?, but I need the webpage to work locally on the computer, and this does not seem to work then.

Is there any way to achieve this?

Community
  • 1
  • 1
user2370460
  • 7,470
  • 10
  • 31
  • 46

1 Answers1

0

There's nothing wrong with your code, it's the way you're using it. Use this code instead:

function imageExists(url)
{
    url = window.location.protocol + window.location.host + url;
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}
DividedByZero
  • 4,333
  • 2
  • 19
  • 33
  • Hi, I can't get this to work; when I use imageExists("images/image1.png") I get the following error message in the console: "XMLHttpRequest cannot load file:///Users/dferguson11/Desktop/images/image1.png. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource." Can you tell me how to fix this? – user2370460 Oct 22 '14 at 07:18
  • this is only supported on localhost and domains like: `www.example.com`. not without a server – DividedByZero Oct 22 '14 at 15:34