0

I have a portion of code that depends on knowing the width of an image on my page.

If I fire it immediately (at the top of $(function(){ it sometimes doesn't work, as the image hasn't loaded yet.

If I use jquery (I'm already using it for other stuff on the page) to fire on load(), it NEVER fires. Presumably because the image has loaded before the JS even executes, or because it's cached.

$('#photo').load(function(){
    alert('loaded');
});
//doesn't fire

If I do the following, it does work, but after a noticeable delay while it fetches the image for the second time:

$('#photo').load(function(){
    alert('loaded');
});
$('#photo').attr('src',$('#photo').attr('src')+'?'+new Date().getTime());
//fires, but is slow

Surely in 2016 there must be a nice way of doing this? Either in jquery or vanilla JS.

Codemonkey
  • 4,455
  • 5
  • 44
  • 76
  • please provide a [mcve] – Daniel A. White Feb 24 '16 at 11:55
  • what if you wait until the DOM is fully loaded by using the document ready function ? (https://api.jquery.com/ready/) – DTH Feb 24 '16 at 11:55
  • Or if you want to do it as soon as image has loaded see this previous SO post (http://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached) – DTH Feb 24 '16 at 12:01

3 Answers3

3

Why not simply use onLoad function of the image:

<img src="/path/to/image.jpg" onload="doStuff(this);" />

It will trigger once the image has loaded ..

DTH
  • 1,133
  • 3
  • 16
  • 36
0

You could use the Unveil plugin to trigger a callback once your image has been loaded. As a bonus you'll also get lazyloading!

$("img").unveil(200, function() {
  $(this).load(function() {
    // where you do your things... this = the image object
  });
});
kuzyn
  • 1,905
  • 18
  • 30
0

I'm using the following:

$('<img />').one('load', function() {
  // do stuff
}).attr('src', $('#photo').src);

Create a tag, attach a one time onload handler to it and only then tell it what the src url is.

Another approach would be:

$('#photo').on("load",function(){
  // do stuff
}).each(function(){
  if(this.complete) {
    $(this).trigger('load');
  }
});

The idea here is that the chaining ensures that if the photo is in the cache and the onload handler is attached too late to catch it, the each(this.complete) section will save the day and fire the onload.

Do these meet your definition of fast?

alfred_j_kwack
  • 1,665
  • 2
  • 11
  • 7