javascript - $(window).on ('load' ) 在 jQuery(document).ready() 中没有被正确调用

标签 javascript jquery

我以前在我的 JavaScript 文件中有这段代码,它曾经工作...

jQuery(document).ready(function ($) {
    "use strict";

    $(window).load(function (event) {
        LoadPage();
    });

将 jQuery 更新到版本 3.3.1 后,我不得不将 $(window).load 替换为 $(window).on('load') 因为它已弃用。所以这是新代码:

jQuery(document).ready(function ($) {
    "use strict";

    $(window).on('load', function (event) {
        LoadPage();
    });

问题是这个新代码,并不总是按预期运行...在 Chrome 中,LoadPage() 方法按预期调用。如果我使用 MS Edge,它根本不会点击 LoadPage() 方法。如果我使用 Chrome 隐身模式,它有时会点击该方法,有时不会...知道为什么会这样吗?

最佳答案

好的,我在这里找到了答案:jQuery 3 - Github Issues

这是 jQuery 核心团队 的 Timmy Willison 的解释:

To be clear, we understand what's causing this. We recently made ready handlers fire asynchronously. This has advantages that are hard to give up. The disadvantage is that the ready handler can sometimes fire after the load event if the load event fires quickly enough. The side effect you're seeing in this issue is that you're binding a load event handler after the load event has already fired.

The fix is to bind the load outside of ready:

函数应该这样调用:

$(function() {
  // Things that need to happen when the document is ready
});

$(window).on("load", function() {
  // Things that need to happen after full load
});

关于javascript - $(window).on ('load' ) 在 jQuery(document).ready() 中没有被正确调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48717531/

相关文章:

javascript - 编辑文件-纯js

javascript - 使用javascript在php中计时器达到零时不调用提交方法

jquery 显示是否来自特定链接

javascript - 为什么在没有发出双击时进入 dblclick 处理程序?

javascript - 在文本区域中显示页面行

javascript - 更改字体系列后调整所有字体大小

javascript - Ant Design(antd)的分页和卡片组件?

javascript - 我怎样才能顺利地 "pinch"一个包含文本的元素?

javascript - 显示或隐藏对象时切换按钮

javascript - 在悬停时显示另一个 div