0

My javascript code requires an image to load before it can proceed with the rest of the script:

var myImage = new Image();
myImage.onload = function() {
   executeRemainingCode();
};
myImage.src = myImgURL;

function executeRemainingCode() {
// 2,000 lines of remaining code to execute
}

It works fine, however, I would prefer not to wrap thousands of lines of remaining code into a function. It makes the indentation and parentheses more complicated for the entire script.

Is there a way to delay execution of the remaining code, without wrapping it all in a function?

jm92
  • 137
  • 10
  • If that's suitable to you, you can wait for the 'load' event, it will be triggered when everyting is loaded including images – Lk77 Dec 28 '22 at 17:10

1 Answers1

2

You can use promise

@Sebastian Simon You can simply use top-level await instead.

const ImagePromise = (src) => new Promise((resolve) => {
  const myImage = new Image();
  
  myImage.onload = () => {
   resolve();
  };

  myImage.src = src;
})

await ImagePromise(myImageUrl)

// 2,000 lines of remaining code to execute
kennarddh
  • 2,186
  • 2
  • 6
  • 21