1

Below is my code that I execute:

    <head>
        <script>
            function uploadFile() {
                console.log('here');
                var x = document.getElementById('img');
                console.log(x.files);

                var _URL = window.URL || window.webkitURL;
                var file = x.files.item(0);
                var img = new Image();
                img.src = _URL.createObjectURL(file);
                img.onload = function () {
                    alert("alert1 : this alert should come before");
                    alert(this.width + " " + this.height);
                }
                alert("alert2: this alert should come later");
            }
        </script>
    </head>
    <body>
        <input type='file' id='img' accept="image/*"/>
        <input type='submit' value='Upload' onclick='uploadFile()'/>    
    </body>
<html>

I want alert1 to be displayed before alert2.

Currently, first alert2 is displayed before alert1.

  • 2
    You don’t execute the onload function. It executes when the image loads. You don’t know when that will be, which is why you pass in a callback function. If you want alert2 to fire after this it needs to be in that callback. – Mark Dec 03 '19 at 07:00
  • you would probably need to look at Promises if you need to trigger things in particlar sequence – Professor Abronsius Dec 03 '19 at 07:33

2 Answers2

1

How docs for image.onload says:

This event handler will be called on the image element when the image has finished loading

It seems that the image wasn't loaded before the second alert was executed. You can check that the image is loaded and after that handle it in your way.

funnydman
  • 9,083
  • 4
  • 40
  • 55
0

This is the only way to show alert2 second. Because alert1 is depended on image load.

img.onload = function () {
    alert("alert1 : this alert should come before");
    alert(this.width + " " + this.height);
    alert("alert2: this alert should come later");
}