javascriptjqueryajaxbroken-linksbroken-image

Detect broken image and get src's using jquery


I have detected broken images and getting broken src's and store them into the object but unable to store them into an object because of I think there is a time difference between error function and catching them into object please check my code.

I successfully get src but unable to store them in object variable and passing them into backend via ajax. By debugging testing it I think

brokenImages.current_url = currentUrl;  
brokenImages.broken_src = brokenSrc;

Run before error function and I get nothing in brokenImages variable.

jQuery(document).ready(function($){

        //Check Image Error
        var i = 0;
        var currentUrl = window.location.href;
        var brokenImages = new Object();
        var brokenSrc = new Object();


        $('img').on('error', function(event){

            var link = event.target.src;

            console.log('check '+link + ' num ' + i);

            brokenSrc[i] = link;

            i++;
        });

        //alert(brokenSrc);

        //Like if I put alert brokenSrc object here I get them in ajax and php

        console.log(' broken src ');
        console.log(brokenSrc);

        brokenImages.current_url = currentUrl;  
        brokenImages.broken_src = brokenSrc;

        console.log( ' broken images ' );
        console.log(brokenImages);

//In console log of chrome and firefox I can see object and srcs in them but when ajax sending them and catching them into php there is nothing broken_src

        //Sent Script Data
        $.ajax({
            type: "POST",
            url: ajax_url,
            data: {
                imageData: brokenImages
            },
            success: function(result){
                console.log(result);
            }
        });

});

Unable to store them in brokenImages variables while successfully getting them.


Solution

  • .error is deprecated, need to use .on('event' instead.

    Allow error is asynchronous, your code is not waiting for images to get loaded to send final report of broken images. Also empty src attribute on img will not trigger error or success, you need to ignore or add them separately. I have ignored them in below code.

    $(document).ready(function() {
    
        //Check Image Error
        var i = 0;
        var brokenSrc = [];
    
        var totalImagesOnPage = $('img').not( "[src='']" ).length;
    
        $('img').on('load', function() {
            increaseCount();
        }).on('error', function() {
            var link = $(this).attr('src');
            console.log('broken link : ' + link);
            brokenSrc.push(link);
            increaseCount();
        });
    
    
        function increaseCount() {
            i++;
            if (i == totalImagesOnPage) {
                finishedLoadingImages();
            }
        }
    
        function finishedLoadingImages() {
            console.log("Broken images ::", brokenSrc);
            $.ajax({
                type: "POST",
                url: '/',
                data: {
                    imageData: {
                        current_url: window.location.href,
                        broken_src: brokenSrc
                    }
                },
                success: function(result) {
                    console.log(result);
                }
            });
        }
    
    });
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
      <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    </head>
    <body>
    
    
    <img src="" />
    <img src="http://google.com" />
    <img src="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2014/05/1399880336proe-pic_400x400-96x96.jpg" />
    <img src="https://simplyaccessible.com/wordpress/wp-content/themes/sa-wp-2014/images/logo.svg"/>
    
     </body>
    </html>