Search code examples
javascriptimagesame-origin-policy

Check if series of images exists, stop when not found in Javascript


I'd like to show series of dynamically loaded images named in a structured way in my website. Images are located in a different domain which causes Same Origin Policy restriction. I cannot use $.ajax.

I build my url like with a counter such as www.example.com/Images/img-1.jpg, www.example.com/Images/img-2.jpg and it goes...

I've tried several other answers from similar posts but couldn't make them work. Either the loop runs forever or it never finds the images even though they exist in the path.

1st try:

ShowImages: function () {   
    var urlBase = 'http://www.example.com/Images/img-';
    var i = 1;

    while (true) {
        var url = urlBase + i + '.jpg';     

        var imgDom = new Image();
        imgDom.onload = function () {
            alert('worked');
            i++;
        };
        imgDom.onerror = function () {
            return; // I want to either break the while loop, or return from ShowImages function
        };
        imgDom.src = url;
    }
},

It never hits the .onerror.

2nd try:

ShowImages: function () {   
    var urlBase = 'http://www.example.com/Images/img-';
    var i = 1;

    while (true) {
        var url = urlBase + i + '.jpg';     

        var imgDom = document.createElement("img");
        $(imgDom).attr('src', url);

        if (imgDom.complete) {
            alert('worked');
            i++;
        } else {
            break;
        }
    }
},

It never hits the .complete.


Solution

  • Trying with your first option (you basically need to chain them)

    ShowImages(1);
    ShowImages: function (counter) {   
        var urlBase = 'http://www.example.com/Images/img-';
    
            var url = urlBase + counter + '.jpg';     
    
            var imgDom = new Image();
            imgDom.onload = function () {
                alert('worked');
                ShowImages(counter+1);
            };
            imgDom.onerror = function () {
                alert("all images done..");
                return; // I want to either break the while loop, or return from ShowImages function
            };
            imgDom.src = url;
    };