const myImage = document.querySelector("#my-image");
myImage.src = "selfie.jpg";
I was told the above code is asynchronous. Is it asynchronous?
I thought that I am simply setting the src property on myImage object. I'm not using callback or promise. It's a simple 2 lines of code. So I think it's synchronous. Am I missing something?
CodePudding user response:
That all depends on what you mean by "assignment of .src".
The HTMLImageElement.src
IDL attribute is actually quite complex with this regard.
Setting it will update the attribute value (synchronously), it will also trigger the "update the image data" algorithm. In this algorithm, a new Request will be prepared, but actually sent only at the next microtask, in order to let the script also change the srcset
or crossorigin
values, or even the src
itself.
Then the fetching of the resource and the decoding of the image will both be completly asynchronous.
So yes, if you see the DOM as a JS object, the .src
property is being set synchronously, but this is missing most of the point of this property.
CodePudding user response:
Your code is sync but the execution very likely isn't.
Basically the browser must perform a GET request in order to render your image "selfie.jpg". The browser "decides" how to render it.
You may want to refer to img attribute "decoding" for more insight and tweeking.
MDN Web Docs says:
Provides an image decoding hint to the browser. Allowed values:
sync Decode the image synchronously, for atomic presentation with other content. async Decode the image asynchronously, to reduce delay in presenting other content. auto Default: no preference for the decoding mode. The browser decides what is best for the user.