是否可以在加载任何图像之前运行JavaScript?

是否可以在加载任何图像之前运行JavaScript?

问题描述:

是否可以在加载任何图像之前运行JavaScript?

Is it possible to run JavaScript before any image loads?

这是默认行为吗? Dom,脚本,IMG加载?

Is this default behavior? Dom, script, IMG load?

默认情况下,在图像加载之前运行Javascript。图像加载完成后,窗口对象的加载事件将触发(对于大多数客户端;某些版本的Safari已解雇在图片完成之前加载,但你没有义务等待该事件运行代码。

Javascript runs before images have loaded by default. The window object's load event fires when images have completed loading (for most clients; some versions of Safari have fired load before images complete), but you're in no way obligated to wait for that event to run code.

当假定DOM准备好进行完全交互时,jQuery ready 事件(如另一个注释中所示)触发(在某些客户端中,DOM逐渐准备好进行交互,因为它被解析)。这也没有必要,具体取决于你想要运行的代码。

The jQuery ready event (as seen in another comment) fires when the DOM is assumed to be ready for complete interaction (and in some clients, the DOM is progressively ready for interaction as it is parsed). It's also not necessary, depending on what code you want to run.


  • 如果你想运行不依赖的代码在文档上,您可以随时在任何脚本标记中运行它,并在脚本下载和解析后立即运行。

  • 如果你想运行依赖于DOM而不是图像的代码(或者必然是样式),你会想要寻找一个浏览器DOM-load事件模拟器(类似于这个但不一定是,有很多那里的实现)。

  • 如果您希望在页面加载完成后运行代码,您将需要使用加载事件(并且你想要在周围使用一个抽象window.addEventListener() window.attachEvent(),而不是分配给 window.onload

  • If you want to run code that doesn't depend on the document at all, you can run it in any script tag at any time and it will run immediately as soon as the script is downloaded and parsed.
  • If you want to run code that depends on the DOM but not on images (or, necessarily, styles), you will want to look for a cross-browser DOM-load event simulator (similar to this but not necessarily that, there are a lot of implementations out there).
  • If you want to run code when the page has finished loading, you'll want to use the load event (and you'll want to use an abstraction around window.addEventListener() and window.attachEvent(), rather than assigning to window.onload.