document.onload不适合我吗? [英] document.onload not working for me?

查看:82
本文介绍了document.onload不适合我吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我只是在玩一个GreaseMonkey的用户脚本,这里只是我想做的一些简单的事情;

Well I'm simply playing around with a userscript of GreaseMonkey and here's just something simple I attempt to do;

function test() {
document.getElementById('elementhere').innerHTML = 'test';
}
document.onload = test();

如果我转到我想要使用的页面并且运行或重新加载和运行 - 但它不会自动运行,我试图通过使用document.onload来实现。

It works if I go to the page I want to use it on and do "run" or "reload & run" - but it won't run automatically, which I'm trying to make it do by using document.onload.

推荐答案

你需要的是:

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

document.onload 它不存在。如果您至少从文档中定位某些特定元素,例如:

document.onload it doesn't exist. It works if you at least target some specific element from document for example:

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

你如果你想在DOM是唯一的元素就绪之后执行一些代码而没有等待加载媒体元素,那么还有其他选择:

You have other options if you want to execute some code after the DOM is the only element ready without wait for media elements to load like:


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

如果你再看一遍 MDN文档他们会在 Notes 部分推荐您使用可由addEventListener处理的DOMContentLoaded和DOMFrameContentLoaded事件。所以,如果你这样做:

If you take a look again in MDN documentation they will recommend you in section Notes to use DOMContentLoaded and DOMFrameContentLoaded events which can be handling by addEventListener. So, if you do this:

document.addEventListener('DOMContentLoaded',handlerFunc);

document.addEventListener('DOMContentLoaded', handlerFunc);

适合您。

我希望这对您有所帮助...

I hope this can be helpful for you...

这篇关于document.onload不适合我吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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