¿Cómo puedo determinar si una imagen se ha cargado, usando Javascript / jQuery?


Estoy escribiendo Javascript para cambiar el tamaño de la imagen grande para que quepa en la ventana del navegador del usuario. (Desafortunadamente, no controlo el tamaño de las imágenes de origen.)

Así que algo como esto estaría en el HTML:

<img id="photo"
     src="a_really_big_file.jpg"
     alt="this is some alt text"
     title="this is some title text" />

¿Hay alguna manera para mí de determinar si la imagen src en una etiqueta img se ha descargado?

Necesito esto porque me estoy topando con un problema si $(document).ready() se ejecuta antes de que el navegador haya cargado la imagen. $("#photo").width() y $("#photo").height() volverá el tamaño del marcador de posición (el texto alternativo). En mi caso esto es algo así como 134 x 20.

Ahora mismo solo estoy comprobando si la altura de la foto es inferior a 150, y suponiendo que si es así es solo texto alternativo. Pero esto es todo un truco, y se rompería si una foto tiene menos de 150 píxeles de altura (no es probable en mi caso particular), o si el texto alternativo tiene más de 150 píxeles de altura (posiblemente podría ocurrir en una pequeña ventana del navegador).


Editar: Para cualquiera que quiera ver el código:

$(function()
{
  var REAL_WIDTH = $("#photo").width();
  var REAL_HEIGHT = $("#photo").height();

  $(window).resize(adjust_photo_size);
  adjust_photo_size();

  function adjust_photo_size()
  {
    if(REAL_HEIGHT < 150)
    {
      REAL_WIDTH = $("#photo").width();
      REAL_HEIGHT = $("#photo").height();
      if(REAL_HEIGHT < 150)
      {
        //image not loaded.. try again in a quarter-second
        setTimeout(adjust_photo_size, 250);
        return;
      }
    }

    var new_width = . . . ;
    var new_height = . . . ;

    $("#photo").width(Math.round(new_width));
    $("#photo").height(Math.round(new_height));
  }

});

Actualización: Gracias por las sugerencias. Existe el riesgo de que el evento no se active si establezco una devolución de llamada para el evento $("#photo").load, por lo que he definido un evento onLoad directamente en la etiqueta de imagen. Para que conste, aquí está el código con el que terminé yendo:

<img id="photo"
     onload="photoLoaded();"
     src="a_really_big_file.jpg"
     alt="this is some alt text"
     title="this is some title text" />

Luego en Javascript:

//This must be outside $() because it may get called first
var isPhotoLoaded = false;
function photoLoaded()
{
  isPhotoLoaded = true;
}

$(function()
{
  //Hides scrollbars, so we can resize properly.  Set with JS instead of
  //  CSS so that page doesn't break with JS disabled.
  $("body").css("overflow", "hidden");

  var REAL_WIDTH = -1;
  var REAL_HEIGHT = -1;

  $(window).resize(adjust_photo_size);
  adjust_photo_size();

  function adjust_photo_size()
  {
    if(!isPhotoLoaded)
    {
      //image not loaded.. try again in a quarter-second
      setTimeout(adjust_photo_size, 250);
      return;
    }
    else if(REAL_WIDTH < 0)
    {
      //first time in this function since photo loaded
      REAL_WIDTH = $("#photo").width();
      REAL_HEIGHT = $("#photo").height();
    }

    var new_width = . . . ;
    var new_height = . . . ;

    $("#photo").width(Math.round(new_width));
    $("#photo").height(Math.round(new_height));
  }

});
Author: Kip, 0000-00-00

2 answers

O bien agregar un receptor de eventos, o hacer que la imagen se anuncie a sí misma con onload. Luego averigua las dimensiones a partir de ahí.

<img id="photo"
     onload='loaded(this.id)'
     src="a_really_big_file.jpg"
     alt="this is some alt text"
     title="this is some title text" />
 30
Author: Diodeus - James MacFarlane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-04 21:04:44

Usando el almacén de datos de jquery puede definir un estado 'loaded'.

<img id="myimage" onload="$(this).data('loaded', 'loaded');" src="lolcats.jpg" />

Entonces en otra parte se puede hacer:

if ($('#myimage').data('loaded')) {
    // loaded, so do stuff
}
 14
Author: ,
Warning: date() expects parameter 2 to be long, string given in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61