HTML head 之外的窗口加载事件
我正在使用一些旧的 HTML/JS 代码,我需要附加到加载事件。
我正在使用的脚本位于 标记之外。
将事件侦听附加到头部外部时,侦听加载事件是否不可靠?
IE 页面是否已经加载并忽略我的事件侦听器是否有可能?
在我的测试中,事件侦听器被正常触发,但我确定是否一直都是这种情况。
顺便提一句。 由于遗留问题,我需要避免使用 jQuery(这是不愉快的一天)。
I am working with some legacy HTML/JS code, where I need to attach to the load event.
The script I am working with is outside of the <head>
tags.
Is listening to the load event unreliable when attaching the event listening outside of the head?
i.e.
Is it somehow possible that the page already loads and ignores my event listener?
In my testing the event listener is fired fine, but I'm ensure if this is the case all the time.
btw.
Due to the legacy nature I need to avoid using jQuery (an unhappy day).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
?不,如果您真的在谈论
window.onload
,则不可靠。window.onload
发生在整个 HTML 被解析之后(以及图像和样式表等任何外部资源已完全加载之后)。应该没问题。有点偏离主题,但如果您愿意,即使不使用 jQuery,您也可以获得更早的可靠呼叫。只需将其放在结束
标记之前即可:
此时,DOM 为 可靠可用,但调用发生时间比
window.onload
早很多(取决于大小)您的外部资源,甚至可能提前几秒钟)。出于这个原因,Google 的 JavaScript 专家反对 jQuery 风格的“就绪”事件(请参阅上面的链接)。一些“不引人注目的 JavaScript”人不喜欢它(尽管对我来说,这与在head
中放置script
标签没有本质上的区别,只要该函数在您的应用程序中标准化即可;这不像到处都是onclick
属性),但在您继承的这段代码中,听起来那艘船已经航行了。 ;-)No, not if you're literally talking about
window.onload
.window.onload
happens very, very late in the process, after the entire HTML has been parsed (and also after any external resources like images and stylesheets and such have been completely loaded). It should be fine.Somewhat off-topic, but you can get an earlier reliable call if you like even without using jQuery. Just put this just before your closing
</body>
tag:At that point, the DOM is reliably available, but the call happens a lot earlier than
window.onload
(depending on the size of your external resources, possibly even seconds earlier). Google's JavaScript experts argue against the need for a jQuery-style "ready" event (see the link above) for this very reason. Some "unobtrusive JavaScript" folks don't like it (although to me it's not substantially different from putting ascript
tag in thehead
, provided the function is standardized across your app; it's not like sprinklingonclick
attributes all over the place), but it sounds like that ship has already sailed in the case of this code you've inherited. ;-)