Jquery img load error

Better Broken Image Handling Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead, you may want to replace that with a “missing image” graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you […]

Содержание

  1. Better Broken Image Handling
  2. Comments
  3. Chris Tierney
  4. ColdFusion Web Application Server Stack Blog
  5. img Element error Event
  6. .error()
  7. .error( handler ) Returns: jQuery version deprecated: 1.8, removed: 3.0
  8. version added: 1.0 .error( handler )
  9. version added: 1.4.3 .error( [eventData ], handler )
  10. Additional Notes:
  11. Example:
  12. Resource loading: onload and onerror
  13. Loading a script
  14. script.onload
  15. script.onerror
  16. Other resources
  17. Crossorigin policy
  18. How to check Broken Image with jQuery and AJAX
  19. Contents
  20. 1. With jQuery
  21. 2. With jQuery and AJAX
  22. 3. Demo
  23. 4. Conclusion

Better Broken Image Handling

Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead, you may want to replace that with a “missing image” graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you might want to hide it entirely. This is possible because images that a browser can’t find fire off an “error” JavaScript event we can watch for.

Additionally, you may wish to trigger some kind of Ajax action to send an email to a site admin when this occurs.

While this is neat and I didn’t know that imgs threw an error if they can’t be loaded, the usefulness of such a block seems low and somewhat heavy (attaching an event-listener to every img on a page) for something that shouldn’t occur very often.

I could see this being useful in a case where UGC is being created and the user uploads an image, you could try to display the image if its been processed by the server and if not show a placeholder.

In my experience, Chrome and Firefox recognise when images aren’t loaded and log it to the console, not sure about other browsers.

Hi,
This is chandru from Chennai(india)…
You hava a amazing site Every works is useful for me,
keep it up dude…

I really want to implement this on my site, but some of the images are rendered via a PHP script, and this bit of code hides those images for some reason. Can anyone help me out? I don’t like that ugly little icon showing up. I have a image sitting behind where the rendered image should be in case it cannot render it because it is trying to pull down a Minecraft skin and if a user did not upload one the default is not rendered.

Oops, never mind. Works now. Just played around a bit and got it.

Wish you would have provided your solution as I’m having the same problem.

Saddly, this does not work in IE – even through IE 9.

Great!! solved my error 🙂

no it did not on the second glance :((
I am getting missing image icons on my menu hover how can i deal with it??

It doesn’t work for background images.
You’ll have to add some to the script if this is your case.

in chrome (forgot to mention)

Hi all, i cant seem to get this to work. What should the code look like and do i place it before the head or the cose of the body

I was doing something similar to this, but then I found this is a bad choice.

Broken images are not always caused by invalid url or file-not-exist, it could be caused by temporary network problem or slow connection.

By changing image src of a broken image, users won’t get a chance to see what the real scr is (right click – view image info). It’s even worse to hide the broken image because it’s totally invisible.

So my solution is to leave the browser broken image alone, and add a reload-image click event to the image.

For some browsers, you might need to specify dimensions and a border .broken-image , otherwise the image will be invisible. And remove the class on image load.

I don’t have any idea where to paste this code,

Can you please show me more detail?

It’s Actually on Your CSS Stylesheet, But i think Posting this is totally a bad idea.
Why not try putting background-image: url(whatever_image_name_is.jpg);.
If you don’t need a blank space so if image does not properly load the background-image would be there, rather than hiding or replacing image using Jquery.
A developer would totally understand what i mean.
I’m Precious Tom From Nigeria…

…and then it waits for the site to load entirely and hides imgs afterwards.

Might cause flickering but surely hides all that needs to be hidden.

Great solution, however that flickering you are noticing can easily be avoided by not waiting for the document to be ‘ready’ before hiding the images.

Alright, why doesn’t it render markdown codeblocks?

This was just was I didn’t know I needed! I did how ever change a bit of it…. This way the original source would still be visible and right-click should work.

noImg <
position: relative;
border: 1px solid lightgrey;
background-image: url(http://sirsyedcollege.org/wp-content/themes/EducationAcademy/images/no-image_980x516.jpg);
background-position: 50% 50%;
background-repeat: no-repeat;
-moz-background-size: contain;
-o-background-size: contain;
-webkit-background-size: contain;
background-size: contain;
height: 75px;
width: 126px;
content: «»;
margin: 0 10px 10px 0;
>

shorthand

.noImg <
position: relative;
border: 1px solid lightgrey;
background: url(http://sirsyedcollege.org/wp-content/themes/EducationAcademy/images/no-image_980x516.jpg) 50% 50%/contain no-repeat;
height: 75px;
width: 126px;
content: «»;
margin: 0 10px 10px 0;>
PS!
Image credit where image is stolen from, please replace with your own 🙂

Forgot to give credit to Sakknekedro

In Safari 6.0.5, if you don’t use a background image but just a background color, width and height don’t have any effect if using content: «» . Since content: «» is the key factor here to hide both the ? icon and the inner white outline, this works if you just want a custom sized background placeholder:

I went crazy trying to disable this white outline on a broken image, when my Last.fm script didn’t find an album cover so, glad I found this post.

I believe error is deprecated? Wont work in jQuery above 1.8?

Источник

Chris Tierney

ColdFusion Web Application Server Stack Blog

img Element error Event

If you develop and push to production, you most likely have experienced broken images on your dev instance. You may have also run into broken images on production due to user/admin error, etc. Wouldn’t it be nice if you could display a default placeholder image without having to take a hit on your file system, checking to see if it exists, before your load each image?

Thanks to Ryan Stille’s recent blog post, I have been made aware of a (not so great) solution. Apparently the img tag, along with others such as object, script and style have error events. We can listen for the error event and load a placeholder image in place of the default browser error image.

The catch is the event handler must be attached before the browser fires the error event. Also, the error event may not be correctly fired when the page is served locally. The error event relies on HTTP status codes and will generally not be triggered if the URL uses the “file:” protocol.

In simpler terms, the only solution I’ve found is to either place the event handler inline with the img tag, assign the img src via JavaScript or recursively search each image’s complete state or naturalWidth once the window is done loading. I’ve tried using “$().on()” and “$(“img”).error()” both after the document loads and inline before the element is loaded. However neither solution works, which doesn’t make much sense to me.

I am including multiple examples because this is not a one-solution-fits-all scenario.

The first working example displays a placeholder image using the inline method if the error event is thrown. Notice the onerror handler is reset when it’s run so you don’t run into an infinite loop if your placeholder image also fails.

The second working example, also using the inline method, will call a script that will report the broken image and load the placeholder. The script returns an image with the proper image MIME type.

The third working example uses JavaScript to load the image and displays a placeholder if that image fails to load.

The final working example recursively searches through each image after the window loads. If it finds the state incomplete or the natural width of the image is 0, then it loads the placeholder image.

Источник

.error()

.error( handler ) Returns: jQuery version deprecated: 1.8, removed: 3.0

Description: Bind an event handler to the «error» JavaScript event.

version added: 1.0 .error( handler )

version added: 1.4.3 .error( [eventData ], handler )

Note: This API has been removed in jQuery 3.0; please use .on( «error», handler ) instead of .error( handler ) and .trigger( «error» ) instead of .error() .

The error event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly.

For example, consider a page with a simple image element:

The event handler can be bound to the image:

If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:

Handler for .error() called.

The event handler must be attached before the browser fires the error event, which is why the example sets the src attribute after attaching the handler. Also, the error event may not be correctly fired when the page is served locally; error relies on HTTP status codes and will generally not be triggered if the URL uses the file: protocol.

Note: A jQuery error event handler should not be attached to the window object. The browser fires the window ‘s error event when a script error occurs. However, the window error event receives different arguments and has different return value requirements than conventional event handlers. Use window.onerror instead.

Additional Notes:

  • As the .error() method is just a shorthand for .on( «error», handler ) , detaching is possible using .off( «error» ) .

Example:

To replace all the missing images with another, you can update the src attribute inside the callback passed to .error() . Be sure that the replacement image exists; otherwise the error event will be triggered indefinitely.

Источник

Resource loading: onload and onerror

The browser allows us to track the loading of external resources – scripts, iframes, pictures and so on.

There are two events for it:

  • onload – successful load,
  • onerror – an error occurred.

Loading a script

Let’s say we need to load a third-party script and call a function that resides there.

We can load it dynamically, like this:

…But how to run the function that is declared inside that script? We need to wait until the script loads, and only then we can call it.

For our own scripts we could use JavaScript modules here, but they are not widely adopted by third-party libraries.

script.onload

The main helper is the load event. It triggers after the script was loaded and executed.

So in onload we can use script variables, run functions etc.

…And what if the loading failed? For instance, there’s no such script (error 404) or the server is down (unavailable).

script.onerror

Errors that occur during the loading of the script can be tracked in an error event.

For instance, let’s request a script that doesn’t exist:

Please note that we can’t get HTTP error details here. We don’t know if it was an error 404 or 500 or something else. Just that the loading failed.

Events onload / onerror track only the loading itself.

Errors that may occur during script processing and execution are out of scope for these events. That is: if a script loaded successfully, then onload triggers, even if it has programming errors in it. To track script errors, one can use window.onerror global handler.

Other resources

The load and error events also work for other resources, basically for any resource that has an external src .

There are some notes though:

  • Most resources start loading when they are added to the document. But is an exception. It starts loading when it gets a src (*) .
  • For , the iframe.onload event triggers when the iframe loading finished, both for successful load and in case of an error.

That’s for historical reasons.

Crossorigin policy

There’s a rule: scripts from one site can’t access contents of the other site. So, e.g. a script at https://facebook.com can’t read the user’s mailbox at https://gmail.com .

Or, to be more precise, one origin (domain/port/protocol triplet) can’t access the content from another one. So even if we have a subdomain, or just another port, these are different origins with no access to each other.

This rule also affects resources from other domains.

If we’re using a script from another domain, and there’s an error in it, we can’t get error details.

For example, let’s take a script error.js that consists of a single (bad) function call:

Now load it from the same site where it’s located:

Источник

How to check Broken Image with jQuery and AJAX

The images which are wouldn’t successfully load on the web page will show nothing when the source does not exist.

It looks bad when there are many images and some of them are missing.

For solving this you need to look through all the pages and find the broken images and fix them manually time to time. It is a time-consuming process.

In this tutorial, I will show you two examples, to automatically detect the broken images and replace with another image.

  • In the first one, I am using the jQuery, and
  • In the second, using AJAX with jQuery

Contents

1. With jQuery

Bind error event on the img element. It gets triggered when the image will not successfully load on the web page.

Using this to replace the image source with the default image.

Example

With JavaScript

You need to define onerror attribute in the image elements and perform image replace operation.

Problem

Both codes work fine until the replacing image exists on your server. But, by chance, it gets removed or the name of the image is renamed in this case when you load the page you see the flickering effect on the image which does not exist.

This is because when the image does not exist then it triggered error event now when you try to replace the image with another image which also doesn’t exist then it again triggers error event.

It becomes the never-ending loop.

For solving this I am using AJAX.

2. With jQuery and AJAX

Looping through all image elements and sending AJAX GET request to image source for the check if the source exists or not. If it doesn’t exist then it goes to the error function. From their handle the image.

If the replacement file also doesn’t exist then hide the image.

Example

3. Demo

Here, the third image is not available on the server.

4. Conclusion

In the tutorial, I used the error event to update the image source with the default image when the image file doesn’t exist.

You can also handle with AJAX request.

I hope this may help you and if you know some other better solution to check the source of the broken images then let me know in the comment section.

If you found this tutorial helpful then don’t forget to share.

Источник

Нередко бывает, что при загрузке веб-страницы какие-то изображения оказываются недоступны, и браузер услужливо рисует на их месте пустые контуры. В этой статье я расскажу, как обработать ошибки загрузки изображений и подставить вместо них другое изображение.

Допустим, у нас на сервере лежит файл: https://svgshare.com/i/7ck.svg

Рассмотрим следующий пример. Сколько изображений будет показано?

<html>
  <head>
    <meta charset="utf-8" content="text/html; charset=utf-8"/>
    <style>
      html, body {
        height: 100px;
        width: auto;
      }
    </style>
  </head>

  <body>
    <div class="achievement-image">
      <img src="https://svgshare.com/i/7ck.svg">
      <img src="//svgshare.com/i/7ck.svg">
      <img src="svgshare.com/i/7ck.svg">
      <img src="7ck.svg">
    </div>
  </body>
</html>

Одно, максимум два.

Ответ зависит от того, как открыть этот код. Если разместить его на сервере, вроде https://myserver.com, мы увидим первые два изображения. Если же сохранить его локально и открыть в браузере html файл — только одно. Для ясности я покажу, во что превращаются ссылки из атрибута src в обоих случаях.

В случае сервера https://myserver.com имеем:

https://svgshare.com/i/7ck.svg
https://svgshare.com/i/7ck.svg
https://myserver.com/svgshare.com/i/7ck.svg
https://myserver.com/7ck.svg

В случае локального файла из file:///home/leksa/html/example.html имеем:

https://svgshare.com/i/7ck.svg
file://svgshare.com/i/7ck.svg
file:///home/leksa/html/svgshare.com/i/7ck.svg
file:///home/leksa/html/7ck.svg

Для отслеживания и реакции на успешную или неуспешную загрузку изображения HTML предлагает нам два события, доступных для тега img: onload и onerror. Как следует из названия, первое событие возникает, когда изображение было загружено, а второе, когда что-то пошло не так.

Модифицируем наш код и проверим работу этих событий в консоли браузера.

<div class="achievement-image">
  <img src="https://svgshare.com/i/7ck.svg" 
       onload="console.log('load 1')" onerror="console.log('error 1')">
  <img src="//svgshare.com/i/7ck.svg"
       onload="console.log('load 2')" onerror="console.log('error 2')">
  <img src="svgshare.com/i/7ck.svg"
       onload="console.log('load 3')" onerror="console.log('error 3')">
  <img src="7ck.svg"
       onload="console.log('load 4')" onerror="console.log('error 4')">
</div>

Как и ожидалось, последние три изображения спровоцировали событие onerror. Назначим на него свой обработчик (потребуется подключить библиотеку JQuery) и подменим атрибут src на адрес желаемого изображения.

$(document).ready(function() {
  $(".image-container img").each(function(key, item) {
    $(item).on("error", function() {
      showDefaultImage(this);
    }).attr('src', $(item).attr('src'));
  });
});

function showDefaultImage(img) {
  $(img).attr('src', 'https://svgshare.com/i/7bo.svg');
  $(img).off("error");
}

В интернете есть много примеров решения данной задачи, однако есть один важный момент, о котором часто забывают. Хочу обратить ваше внимание на вызов

$(item).on(...).attr('src', $(item).attr('src'))

после назначения обработчика. Атрибут src устанавливается в то же значение, в котором он изначально был. Зачем это нужно?

Для ответа на этот вопрос вернёмся к последовательности возникновения событий.

  • Событие DOMContentLoaded возникает, когда построено дерево DOM, а также загружены и выполнены все скрипты. При этом внешние ресурсы, включая изображения и стили, могут быть ещё не загружены.
  • Событие load объекта window возникает, когда страница со всеми ресурсами была загружена.
  • Событие ready специфично для JQuery, согласно документации, оно аналогично событию DOMContentLoaded, то есть не дожидается загрузки мультимедийного контента.

Откроем код, приведённый ниже, и посмотрим на вывод в консоли браузера.

<html>
  <head>
    <meta charset="utf-8" content="text/html; charset=utf-8"/>

    <style>
      html, body {
        height: 100px;
        width: auto;
      }
    </style>

    <script>
      $(document).on("DOMContentLoaded", function() {
        console.log("document loaded");
      });
      $(window).on("load", function() {
        console.log("content loaded");
      });
      $(document).ready(function() {
        console.log(“JQuery ready”);
      });
    </script>
  </head>

  <body>
    <div class="image-container">
      <img src="https://svgshare.com/i/7ck.svg" 
           onload="console.log('load 1')" onerror="console.log('error 1')">
      <img src="//svgshare.com/i/7ck.svg"
           onload="console.log('load 2')" onerror="console.log('error 2')">
      <img src="svgshare.com/i/7ck.svg"
           onload="console.log('load 3')" onerror="console.log('error 3')">
      <img src="7ck.svg"
           onload="console.log('load 4')" onerror="console.log('error 4')">
    </div>
  </body>
</html>


 

Тут есть кое-что интересное. Вопреки ожиданием, событие ready срабатывает после загрузки всего контента (включая изображения), аналогично событию load. А значит, на момент создания обработчиков, события error и load уже произошли, и обработчики никогда не будут вызваны.

В браузере firefox картина примерно такая же.

Это вынуждает прибегать к не совсем красивому решению, когда мы заставляем браузер загрузить изображения заново, уже после привязки обработчиков, путём установки атрибута src в то же самое значение.

Окончательный вариант кода приведён ниже (живой пример).
 

<html>
  <head>
    <meta charset="utf-8" content="text/html; charset=utf-8"/>

    <style>
      html, body {
        height: 100px;
        width: auto;
      }
    </style>

    <script>
      // $(document).on("DOMContentLoaded", function() {
      $(document).ready(function() {
        $(".image-container img").each(function(key, item) {
          $(item).on("error", function() {
            showDefaultImage(this);
          }).attr('src', $(item).attr('src'));
        });
      });

      function showDefaultImage(img) {
        $(img).attr('src', 'https://svgshare.com/i/7bo.svg');
        $(img).off("error");
      }
    </script>
  </head>

  <body>
    <div class="image-container">
      <img src="https://svgshare.com/i/7ck.svg">
      <img src="//svgshare.com/i/7ck.svg">
      <img src="svgshare.com/i/7ck.svg">
      <img src="7ck.svg">
    </div>
  </body>
</html>

If you develop and push to production, you most likely have experienced broken images on your dev instance. You may have also run into broken images on production due to user/admin error, etc. Wouldn’t it be nice if you could display a default placeholder image without having to take a hit on your file system, checking to see if it exists, before your load each image?

Thanks to Ryan Stille’s recent blog post, I have been made aware of a (not so great) solution. Apparently the img tag, along with others such as object, script and style have error events. We can listen for the error event and load a placeholder image in place of the default browser error image.

The catch is the event handler must be attached before the browser fires the error event. Also, the error event may not be correctly fired when the page is served locally. The error event relies on HTTP status codes and will generally not be triggered if the URL uses the “file:” protocol.

In simpler terms, the only solution I’ve found is to either place the event handler inline with the img tag, assign the img src via JavaScript or recursively search each image’s complete state or naturalWidth once the window is done loading. I’ve tried using “$().on()” and “$(“img”).error()” both after the document loads and inline before the element is loaded. However neither solution works, which doesn’t make much sense to me.

I am including multiple examples because this is not a one-solution-fits-all scenario.

The first working example displays a placeholder image using the inline method if the error event is thrown. Notice the onerror handler is reset when it’s run so you don’t run into an infinite loop if your placeholder image also fails.

<img src="images/myImage.jpg" alt="My Image" onerror="imageError(this)">

<script>
function imageError(element) {
    element.onerror='';
    element.src='/images/imgPlaceholder.png';
}
</script>

The second working example, also using the inline method, will call a script that will report the broken image and load the placeholder. The script returns an image with the proper image MIME type.

<img src="images/myImage.jpg" alt="My Image" onerror="imageError(this)">

<script>
function imageError(element) {
    element.onerror='';
    element.src='logBrokenImage.cfm?image=' + element.src';
}
</script>

The third working example uses JavaScript to load the image and displays a placeholder if that image fails to load.

<img id="myImage">

<script>
    $('img').one( 'error', function() {
        $(this).attr( 'src', '/images/imgPlaceholder.png' );
    });

    $('#myImage').attr( 'src', 'myImage.jpg' );
</script>

The final working example recursively searches through each image after the window loads. If it finds the state incomplete or the natural width of the image is 0, then it loads the placeholder image.

<img src="images/myImage.jpg" alt="My Image">

<script>
$(window).load(function() {
    $('img').each(function() {
        if ( !this.complete || ( !$.browser.msie && ( typeof this.naturalWidth == "undefined" || this.naturalWidth == 0 ) ) ) {
            this.src = '/images/imgPlaceholder.png';
        }
    });
});
</script>

#error, #event, #handler, #img, #javascript, #jquery, #src

.error( handler )Returns: jQueryversion deprecated: 1.8, removed: 3.0

Description: Bind an event handler to the «error» JavaScript event.

  • version added: 1.0.error( handler )

    • handler

      A function to execute when the event is triggered.

  • version added: 1.4.3.error( [eventData ], handler )

    • eventData

      An object containing data that will be passed to the event handler.

    • handler

      A function to execute each time the event is triggered.

Note: This API has been removed in jQuery 3.0; please use .on( "error", handler ) instead of .error( handler ) and .trigger( "error" ) instead of .error().

The error event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly.

For example, consider a page with a simple image element:

1

<img alt="Book" id="book">

The event handler can be bound to the image:

1

2

3

4

5

alert( "Handler for .error() called." )

.attr( "src", "missing.png" );

If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:

Handler for .error() called.

The event handler must be attached before the browser fires the error event, which is why the example sets the src attribute after attaching the handler. Also, the error event may not be correctly fired when the page is served locally; error relies on HTTP status codes and will generally not be triggered if the URL uses the file: protocol.

Note: A jQuery error event handler should not be attached to the window object. The browser fires the window‘s error event when a script error occurs. However, the window error event receives different arguments and has different return value requirements than conventional event handlers. Use window.onerror instead.

Additional Notes:

  • As the .error() method is just a shorthand for .on( "error", handler ), detaching is possible using .off( "error" ).

Example:

To replace all the missing images with another, you can update the src attribute inside the callback passed to .error(). Be sure that the replacement image exists; otherwise the error event will be triggered indefinitely.

1

2

3

4

5

6

// If missing.png is missing, it is replaced by replacement.png

$( this ).attr( "src", "replacement.png" );

.attr( "src", "missing.png" );

Понравилась статья? Поделить с друзьями:
  • Jquery get fail error
  • Jquery get error message
  • Jquery event error
  • Jquery error is not a function
  • Jquery ajax success error