如何知道窗口是否“加载"事件已经被触发 [英] How to know if window "load" event was fired already

查看:31
本文介绍了如何知道窗口是否“加载"事件已经被触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Javascript 脚本.此脚本可能会异步加载(AMD 格式).

I'm writing a Javascript script. This script will probably be loaded asynchronously (AMD format).

在这个脚本中,在 window.load 事件被触发之前,我不想做任何重要的事情.所以我听窗口加载"事件.

In this script, I'd like to do nothing important until the window.load event was fired. So I listen to the window "load" event.

但是如果脚本是在 window.load 事件之后加载的...我怎么知道 window.load 已经被触发了?

But if the script is loaded after window.load event... how can I know window.load was already fired?

当然我不想在任何其他脚本中添加一些东西(它们都是异步加载的,问题是一样的):)

And of course I don't want to add something in any other scripts (they are all loaded async, the problem is the same) :)

想象一个完全没有 Javascript 的 HTML 文档.

Imagine an HTML doc with no Javascript in it at all.

有人在这个文档中插入了一个标签,这个脚本标签加载了我的 Javascript 文件.

Than someone insert in this doc a tag, and this script tag loads my Javascript file.

这将执行我的脚本.

这个脚本如何知道 window.load 是否已经被触发?

How this script can know if window.load was already fired ?

没有 jQuery,也没有我之前的 HTML 文档中的任何脚本.

No jQuery, not any script in the HTML doc before mine.

有可能知道吗??

我找到了 window.document.readystate 属性.我猜这个属性是用于文档就绪"事件,而不是用于窗口加载".窗口加载"事件有什么类似的吗?

I found the window.document.readystate property. This property is for document "ready" event I guess, not for window "load". Is there anything similar for window "load" event ?

推荐答案

浏览器 导航性能 loadEventEnd 指标可用于确定是否触发了加载事件:

Browser navigation performance loadEventEnd metric can be used to determinate if load event was triggered:

let navData = window.performance.getEntriesByType("navigation");
if (navData.length > 0 && navData[0].loadEventEnd > 0)
{
    console.log('Document is loaded');
} else {
    console.log('Document is not loaded');
}

这篇关于如何知道窗口是否“加载"事件已经被触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆