+ 9

Help needed: JavaScript .onload and code readability

Whenever I call for updates to HTML elements, the program doesn't wait for them to update and keeps running. Example: var img = new Image(); img.src = "something"; alert(img.height); This code is easy to read because it can be read top-to-bottom. The 1st line is run first, then 2nd, then 3rd. Unfortunately, it doesn't work. It will always output 0 because alert() is called before img is actually updated. [continued in the comments]

5th May 2018, 11:31 PM
Augustinas Lukauskas
Augustinas Lukauskas - avatar
2 Answers
+ 11
[Continuation] That's why I have to use this code instead: var img = new Image(); img.onload = function () { alert(img.height); } img.src = "something"; Notice that the 1st line is run first, then 5th, then 3rd. Often I have to use .onload multiple times in my codes. The longer the code, the longer I have to scroll up and down to be able to read my code in its running sequence. Also after each .onload statement THE ENTIRE following code gets idented right. I came up with some solutions, but all of them are bad. Example: async function () { var img = new Image(); function func() { img.src = "something"; return new Promise(resolve => setTimeout(resolve, 1000)); } await func(); alert(img.height); } Are there any good alternatives?
5th May 2018, 11:34 PM
Augustinas Lukauskas
Augustinas Lukauskas - avatar
+ 1
Images info are avaible only when it get fully and correctly loaded then the .onload callback its the right chooice... Anway which is your goal?
20th Jun 2018, 10:37 PM
KrOW
KrOW - avatar