Posted By

tennison on 09/13/10


Tagged

js jquery images img loading loaded


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

randylien
wirenaught


JS detect if img loaded


 / Published in: JavaScript
 

URL: http://github.com/peol/jquery.imgloaded/blob/master/ahpi.imgload.js

  1. /*
  2.  * Special event for image load events
  3.  * Needed because some browsers does not trigger the event on cached images.
  4.  
  5.  * MIT License
  6.  * Paul Irish | @paul_irish | www.paulirish.com
  7.  * Andree Hansson | @peolanha | www.andreehansson.se
  8.  * 2010.
  9.  *
  10.  * Usage:
  11.  * $(images).bind('load', function (e) {
  12.  * // Do stuff on load
  13.  * });
  14.  *
  15.  * Note that you can bind the 'error' event on data uri images, this will trigger when
  16.  * data uri images isn't supported.
  17.  *
  18.  * Tested in:
  19.  * FF 3+
  20.  * IE 6-8
  21.  * Chromium 5-6
  22.  * Opera 9-10
  23.  */
  24. (function ($) {
  25. $.event.special.load = {
  26. add: function (hollaback) {
  27. if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) {
  28. // Image is already complete, fire the hollaback (fixes browser issues were cached
  29. // images isn't triggering the load event)
  30. if ( this.complete || this.readyState === 4 ) {
  31. hollaback.handler.apply(this);
  32. }
  33.  
  34. // Check if data URI images is supported, fire 'error' event if not
  35. else if ( this.readyState === 'uninitialized' && this.src.indexOf('data:') === 0 ) {
  36. $(this).trigger('error');
  37. }
  38.  
  39. else {
  40. $(this).bind('load', hollaback.handler);
  41. }
  42. }
  43. }
  44. };
  45. }(jQuery));

Report this snippet  

You need to login to post a comment.