Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check image url is 404 using javascript

Use Case:

  1. when src is not null and alt tag is not null then show image of src.
  2. then check src image url is not 404.
  3. when src is null and alt is not null the show image of first name.
  4. when src and alt are null then show default image

HTML:

<img class="imagelazy" id="lazyimage" src="http://url" alt="ankit">

Javascript:

function imagelazy() {

    $(document).ready(function()

        {
            var image = $(".imagelazy").attr('src');
            var altdata = $(".imagelazy").attr('alt');
            var alt = $(".imagelazy").attr('alt').split("");
            //var imagepath="http://im.gifbt.com/userimages/"+alt[0].toLowerCase()+".jpg";
            var defaultimage = "http://im.gifbt.com/img/no-pic.jpg";
            console.log(image);
            console.log(alt);
            $(".imagelazy img")
                .error(function() {
                    $(this).hide();
                })
                .attr("src", defaultimage);

            if (image != '' && altdata != '') {
                console.log("afeef");
                $('.imagelazy').bind('error', function() {
                    $(this).attr("src", defaultimage);
                });
                $(".imagelazy img")
                    .error(function() {
                        $(this).hide();
                    })
                    .attr("src", defaultimage);


            } else if (image == '' && altdata != '') {
                $.each($('.imagelazy'), function(index, value) {
                    var alt1 = $(this).attr('alt').split("");
                    console.log(alt1);
                    if (alt1 != '') {
                        var imagepath1 = "http://im.gifbt.com/userimages/" + alt1[0].toLowerCase() + ".jpg";
                    }
                    console.log(this.outerHTML);
                    console.log(imagepath1);
                    $(this).attr("src", imagepath1);
                });


            } else if (altdata == '' && image == '') {
                $.each($('.imagelazy'), function(index, value) {
                    $(this).attr("src", defaultimage);
                    console.log(this.outerHTML);
                });
            }

        });
}

Problem

  • Script is not working when scrolling down the page.
  • When the image is set in src and alt tag is set then also first name image is displayed.
  • onerror is not working in js.
  • i have googled a lot coudln"t found the solution for this issue.
  • i have found lazy.min.js js which set src="" and data-src="pathimage" would handled this issue.
  • our requirement is optimize html that why im searching for alternate solution through js.

  • i have found jquery link : https://api.jquery.com/error/

like image 428
afeef Avatar asked Aug 11 '15 08:08

afeef


People also ask

How can I tell if a page is 404 in Javascript?

If you have ever wanted to check whether a page has returned a 404 for any reason, one of the easiest ways is to use this little helper function UrlExists() with the current url, given by window. location. href. This will return a true if the http status is anything except a 404, otherwise it will return false .

How do I validate an image url?

To check if a url is an image, call the test() method on a regular expression that matches an image extension at the end of a string, e.g. . png or . jpg . The test() method will check if the url ends with an image extension and will return true if it does.


2 Answers

jQuery Ajax:

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function()
    {
        //file not exists
    },
    success: function()
    {
        //file exists
    }
});

Javascript:

function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

Image check:

function ImageExist(url) 
{
   var img = new Image();
   img.src = url;
   return img.height != 0;
}

Other:

$.get(url)
    .done(function() { 
        // exists code 
    }).fail(function() { 
        // not exists code
    })

HTML:

<img src="image.gif" onerror="imgError()" />

function imgError()
{
alert('The image could not be loaded.');
}
like image 108
Arun Kumar Avatar answered Oct 24 '22 00:10

Arun Kumar


Use onerror event of HTML img tag for 2,3 and 4th scenerio. http://www.w3schools.com/jsref/event_onerror.asp

<img src="invalid_link" onerror="this.onerror=null;this.src='https://www.google.com/images/srpr/logo11w.png';" alt="">
like image 36
Vishnu Atrai Avatar answered Oct 24 '22 00:10

Vishnu Atrai