为什么windows.onload被执行了好几次? [英] Why windows.onload is executed several times?

查看:1135
本文介绍了为什么windows.onload被执行了好几次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绑定像这样的window.onload事件

I'm binding the window.onload event like this

// It's a little more complex than this, I analyze if there is any other function 
// attached but for the sake of the question it's ok, this behaves the same.
window.onload = myfunction; 

在生产服务器上多次在本地计算机上触发Onload

Onload is triggered twice on my local machine a several times on the production server

如果我用jQuery等价物改变它

If I change it by the jQuery equivalent

$jQuery(window).load(myfunction);

表现符合预期(仅执行一次)。

It behaves as expected (executed only once).

你能帮助我理解第一个选项不能正常工作的可能原因吗?

Could you help me to understand possible reasons why the first option it's not working as supposed?

谢谢!

推荐答案

作业中的括号— myfunction()—执行你的功能。您还没有显示 myfunction 的内容,但这意味着该函数的返回值被分配给 window.onload ,而不是功能本身。所以,我不知道如何执行,除非你以某种方式让它工作,比如用结束函数返回这个;

The parentheses on your assignment — myfunction() — executes your function. You haven't shown what myfunction does, but this means that the return value from that function is being assigned to window.onload, not the function itself. So, I don't know how that is getting executed, unless you have somehow got that to work, like ending the function with return this;

你想要

window.onload = myfunction;

鉴于 window.onload 的性质,纯粹的浏览器事件似乎不可能单独进行两个调用 myfunction的。因此,函数内部的断点将帮助您查看调用堆栈。我已经为Chrome添加了屏幕截图。

Given the nature of window.onload, it seems unlikely that pure browser events alone are making both calls to myfunction. Therefore, a breakpoint inside your function will help you see the call stack. I've included screenshots for Chrome.

示例代码:

var alertme = function() {
    alert("Hello");
}

window.onload = alertme;

function testsecondcall() {
    alertme();
}

testsecondcall();




  1. 在Chrome中打开您的页面。

  2. 页面加载一次后,打开开发人员工具面板,在函数内的行上放置一个断点,然后刷新页面。

  3. 检查的调用堆栈两次次破坏。一个将是空的(实际的window.onload)。另一个应该给你一些信息如下:

  1. Open your page in Chrome.
  2. After the page has loaded once, open the Developer Tools panel and put a breakpoint on the line inside your function, then refresh the page.
  3. Check the call stack of both times that it breaks. One will be empty (the actual window.onload). The other should give you some information like the following:

在右侧的调用堆栈下,您会看到 alertme testsecondcall

On the right, under "Call Stack", you see alertme is called by testsecondcall

这篇关于为什么windows.onload被执行了好几次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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