简体   繁体   中英

Why appendChild works asynchronously

In the following code, div.appendChild(img) is not inside reader.onload function which is an asynchronous handler ie runs only when reading file data is complete. That means div.appendChild(img) which is outside & below the reader.onload event should've run before the reader.onload event is complete and thus should show nothing per se.

However, When the the handler for the onload event is complete ie files is read, then div.appendChild(img) fires which means appendChild(img) runs asynchronously. Is this the correct behavior. Please correct if not.

HTML

<input type="file" id="fileInput">   

<div id="demoDiv"></div>

JS

let control = document.getElementById('fileInput') 
let div = document.getElementById('demoDiv') 

control.addEventListener('change', handleFiles)


function handleFiles() {
  let img = document.createElement('img')
  let file = this.files[0]

  let reader = new FileReader(file)
  reader.readAsDataURL(file)
  reader.onload = function() {
    img.src = this.result
  }

  div.appendChild(img)
}

Thanks

This isn't a matter of being synchronous or not, what happens is that img is a pointer to an HTML element, as specified in let img = document.createElement('img') .

When you do this:

div.appendChild(img)

You are appending an element to your div . It doesn't matter when exactly that happens, since you hold the reference to that element. Then, when you do this:

img.src = this.result

You mutate the element which you created. Therefore, regardless of the order in which the operations happen, they will execute correctly.

If div.appendChild(img) happens first, the src will be mutated when the files are read and the image will appear. If not, the src will already be present when the img is appended, and you end with same result.

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