关于javascript:document.onload对我不起作用?

document.onload not working for me?

好吧,我只是在玩GreaseMonkey的用户脚本,这只是我尝试做的简单事情;

1
2
3
4
function test() {
document.getElementById('elementhere').innerHTML = 'test';
}
document.onload = test();

如果我转到要在其上使用它的页面并执行"运行"或"重新加载并运行",它会起作用-但它不会自动运行,而我正尝试通过使用document.onload使其完成。


您需要的是:

1
2
3
window.onload = function () {
// do the work after everything was loaded (DOM, media elements)
}

document.onload它不存在。如果您至少针对文档中的某些特定元素,则可以使用该元素,例如:

1
2
document.querySelector("img").onload = function ()
 {// do your thing after 'img' was loaded}

如果要在DOM是唯一准备就绪的元素之后执行某些代码,而无需等待媒体元素加载,则可以使用其他选项,例如:

  • 导入一个异步脚本标签,并使用以下代码加载文件:
    您可以将此标签放置在DOM中的任何位置,并且不会中断任何内容,不会在DOM完成加载后加载。您应该查看有关此内容的MDN文档。

  • 如果您再次查看MDN文档,他们将在注释部分中建议您使用可以由addEventListener处理的DOMContentLoaded和DOMFrameContentLoaded事件。因此,如果您这样做:

document.addEventListener('DOMContentLoaded',handlerFunc);

将为您工作。

希望对您有帮助...


编写document.onload = test()时,您正在调用test函数,并将其返回值分配给onload处理程序。这显然不是您想要的。

1
document.onload = test;

这会将对test函数的引用分配给onload处理程序。事件触发时,即将调用您的函数。


也许这样做:

1
<body onloadx="test()">

还是那不是您要找的东西?如果您想在没有上面的HTML的情况下进行操作,请尝试用window替换文档:

1
2
3
4
window.onload = function ()
{
   document.getElementById('elementhere').innerHTML = 'test';
}

由于这个原因,我会尝试一下:

window.onload与document.onload

我知道将链接发布到链接是la脚的,但是您将明白我为什么这样做(希望如此)。

干杯!


无需调用页面上的函数..只需要使用下面的代码(这是编码的最佳实践)

1
2
3
4
window.onload = function() {
    document.getElementById("txtCaptcha").value = code;
    document.getElementById("txtCaptchaDiv").innerHTML = code;
    }

这是因为由于最后一行的括号(),所以您要分配test函数的结果而不是函数本身。
删除它们,它可能会起作用。

如果不是,则:

显然,这是设计使然。 [Chrome - v57]
请使用document.addEventListener("DOMContentLoaded", );

请参阅:页面生命周期:DOMContentLoaded


如果您使用的是Greasemonkey,那么您实际上并不需要使用onload事件,因为只有在DOMContentLoaded被触发时才会调用Greasemoneky脚本。

The code in a Greasemonkey user script gets invoked when the
DOMContentLoaded event fires (during event capture as of GM 0.8.6). It
is a DOM event implemented by Mozilla, similar to window.onload.
However, since it waits only for the DOM to load, instead of the
entire page (including images, style sheets, and etc.) it happens
sooner.

http://wiki.greasespot.net/DOMContentLoaded

我认为您只需要在没有任何事件侦听器的情况下调用test()


它正在工作,但您可以使用备用

1
window.init = test;

你有尝试过吗?

1
<body onloadx="test()">

要么

1
2
3
    $(document).ready(function test() {
    document.getElementById('elementhere').innerHTML = 'test';
    }