skatori
skatori

Reputation: 597

How to wait until image.src is set in an image.onload event function?

In my browser javascript for new image() object, for onload event, I first set image.src after user select an image file; then read the size of the image object.

But it seems that the reading occurs before the src is properly set. I happen to find a fix as calling the function twice. But this solution seems a very bad idea.

Please let me know how to fix it in a standard way. My environment accepts Typescript.

var imgLoaded=false;
 var file = document.getElementById("fileInput").files[0];
      for(let i=0;i<2;i++){    
          call2(file);
         }
      

   function call2(file) {
      var reader = new FileReader();
      reader.readAsDataURL(file);

      reader.onload = function () {
          if(!imgLoaded){ 
              imgLoaded=true;   img.src=(reader.result).toString();}
         else{
        console.log(img.width);
      }}

Upvotes: 0

Views: 750

Answers (3)

eiffie
eiffie

Reputation: 46

await (img.src= await (reader.result).toString())

Works as well. No need to invoke the console.

Upvotes: 1

Raya Nasiri
Raya Nasiri

Reputation: 151

In one way you can replace file = document.getElementById("fileInput").files[0]; with file = event.target.files[0] and use it in call2, also you should pass event to call2

for example: in html : <input type="file" onchange="call2(event)" /> , then in js function call2(e){let file = e.target.files[0] ... }

Upvotes: 1

skatori
skatori

Reputation: 597

I found at least a better solution by myself. Although I don't know whether this is a standard or not.


 var file = document.getElementById("fileInput").files[0];
          call2(file);
      

    function call2(file) {
      var reader = new FileReader();
      reader.readAsDataURL(file);

      reader.onload =async function () {
         img.src= await (reader.result).toString();
         console.log(await img.width);
      }}

Upvotes: 1

Related Questions