简体   繁体   English

延迟执行 Javascript 代码直到图像加载

[英]Delay execution of Javascript code until image loads

My javascript code requires an image to load before it can proceed with the rest of the script:我的 javascript 代码需要先加载图像,然后才能继续执行脚本的 rest:

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.它工作正常,但是,我不希望将数千行剩余代码包装到 function 中。这会使整个脚本的缩进和括号更加复杂。

Is there a way to delay execution of the remaining code, without wrapping it all in a function?有没有办法延迟剩余代码的执行,而不用将其全部包装在 function 中?

You can use promise您可以使用 promise

@Sebastian Simon You can simply use top-level await instead. @Sebastian Simon 您可以简单地使用顶级 await代替。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM