简体   繁体   中英

How to fire onload event for Image() on Android with Ionic 3

I'm trying to trigger function on "onload" event of Image() (HTMLImageElement) on Android with Ionic 3. It works with iOS but unfortunately doesn't work with Android.

How can I trigger onload function on Android? I do not use it with <img> or other tag, so I cannot fire it with <img (load)="functionHere()"> .

(I have seen some of the other "onload" questions on Stack Overflow, this is about a specific situation with Android/Ionic 3).

Here is my example code:

this.backgroundImageSource = new Image();
this.backgroundImageSource.src = this.image;


this.backgroundImageSource.onload = function() {
    // THIS PART DOESNT FIRE ON ANDROID
    console.log("ONLOAD TRIGGERED");
}

If the example code is used exactly as shown, then the issue could be with onload event handler being defined after the event could happen. You should define the event handler function before the event could occur.

So onload must be handled before src attribute is set. Although, I'm not sure if the JS engine fixes this in any of its optimization steps.

this.backgroundImageSource = new Image();

//This has to be done before setting src
this.backgroundImageSource.onload = function() {
    console.log("ONLOAD TRIGGERED");
}

this.backgroundImageSource.src = this.image;

I had the same problem.

I discovered that the base64 did not include a header/descriptor and so for that reason it was not firing.

I fixed this by appending a header in cases where one did not exist:

if (!base64Data.includes(',')) {
  // Detect if base64 image is missing header/descriptor
  console.log("Prepending descriptor to Base64 image string")
  base64Data = `data:image/jpeg;base64,${base64Data}`;
}

(The comma is used to separate the header from the body).

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