简体   繁体   中英

Fastest way to fire javascript after an image has been loaded?

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.

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 ..

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
  });
});

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM