0

I want to execute function after image loading finish on selector. How can I achieve this task?

    $('#svg_image').show().attr('src', file);
    return new Promise (function (resolve, reject) {
        $("#svg_image").load(function() {
            resolve({width: $(this).naturalWidth, height: $(this).naturalHeight})
        });
    })
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Rushabh Shah
  • 151
  • 1
  • 5
  • `.load()` as shortcut for load event is deprecated. Where are you returning that promise to? – charlietfl Apr 05 '19 at 11:59
  • Possible duplicate of [Asynchronously load images with jQuery](https://stackoverflow.com/questions/4285042/asynchronously-load-images-with-jquery) – Decay42 Apr 05 '19 at 12:01

3 Answers3

1

You can use the onload event handler, no need for Promise.

The code below loads an image, after load has finished it shows the size, and 2 seconds after that it resizes the image. The delay is just for demo purposes, so you can see the image being resized. Normally you'd use image.onload = SetDimensions;.

var image = $("#img")[0];
image.onload = ShowThenSetDimensions;

image.src = "https://www.gravatar.com/avatar/0a88079f9234aca9f67c04bf7b94eca4?s=32&d=identicon&r=PG&f=1";

function ShowThenSetDimensions() {
  console.log("Size: " + image.naturalWidth + " x " + image.naturalHeight);
  console.log("SetDimensions will be called in 2 seconds");
  window.setTimeout(SetDimensions, 2000);
}

function SetDimensions() {
  image.style.width = image.naturalWidth + "px";
  image.style.height = image.naturalHeight + "px";
  console.log("SetDimensions done");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="img" style="width:10px; height:10px">
Peter B
  • 22,460
  • 5
  • 32
  • 69
  • Good answer. I've one incredibly minor thing to note - I had to check your profile and I wasn't surprised to find that you're active in C# - in JS functions usually start with a lowercase letter :P – VLAZ Apr 05 '19 at 12:08
  • Caught me ;-) well at least I put the curly braces where they 'belong' right? – Peter B Apr 05 '19 at 12:10
  • Heh, I don't think there is a set standard for that in JS :) – VLAZ Apr 05 '19 at 12:11
  • And since using jQuery already can use `$('#img').on('load', function(){ // "this" is the image element})` ... `$('#img').attr(...).on('load',ShowThenSetDimensions)` – charlietfl Apr 05 '19 at 12:12
-2

Please try with this code,

 $("#svg_image").load().then(function(){
 resolve({width: $(this).naturalWidth, height: $(this).naturalHeight})
});
Dhiren
  • 153
  • 1
  • 13
-5

i think you can use setTimeout like :

setTimeout(function(){
 // your code
}, 3000); //3 sec

so your image loading after 3s

LucasLaurens
  • 236
  • 1
  • 3
  • 14