javascript 如何让 Greasemonkey 脚本在 @run-at document-start 和 @run-at document-end 上运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26268816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a Greasemonkey script to run both at @run-at document-start AND at @run-at document-end?
提问by Azevedo
For my Greasemonkey script, there is part of the code that should run before the page is loaded (@run-at document-start
) and another part of the code that should run after the document is loaded (@run-at document-end
).
Is this possible?
对于我的 Greasemonkey 脚本,有一部分代码应该在页面加载之前运行 ( @run-at document-start
),另一部分代码应该在文档加载之后运行 ( @run-at document-end
)。
这可能吗?
- 1st part of script run
- page is loaded, document is ready
- 2nd part of script run
- 脚本运行的第一部分
- 页面已加载,文档已准备就绪
- 脚本运行的第二部分
I'd rather not use jQuery for this.
我宁愿不为此使用 jQuery。
I tried the onload
event but it didn't work. I think the event cannot be attached if the document is not there yet?
我尝试了该onload
事件,但没有奏效。如果文件还没有,我认为无法附加事件?
window.document.onload = function(e){
alert("document.onload" );
}
回答by Brock Adams
The event you want is DOMContentLoaded
. Also, that is not how to use the load
event.
你想要的事件是DOMContentLoaded
. 此外,这不是如何使用load
事件。
Here's a complete script that demonstrates the various firing times:
这是一个完整的脚本,演示了各种触发时间:
// ==UserScript==
// @name _Show page start event timing
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @run-at document-start
// ==/UserScript==
console.log ("==> Script start.", new Date() );
// 1ST PART OF SCRIPT RUN GOES HERE.
console.log ("==> 1st part of script run.", new Date() );
document.addEventListener ("DOMContentLoaded", DOM_ContentReady);
window.addEventListener ("load", pageFullyLoaded);
function DOM_ContentReady () {
// 2ND PART OF SCRIPT RUN GOES HERE.
// This is the equivalent of @run-at document-end
console.log ("==> 2nd part of script run.", new Date() );
}
function pageFullyLoaded () {
console.log ("==> Page is fully loaded, including images.", new Date() );
}
console.log ("==> Script end.", new Date() );
Typical results:
典型结果:
"==> Script start." 2014-10-09T01:53:49.323Z
"==> 1st part of script run." 2014-10-09T01:53:49.323Z
"==> Script end." 2014-10-09T01:53:49.323Z
"==> 2nd part of script run." 2014-10-09T01:53:49.385Z
"==> Page is fully loaded, including images." 2014-10-09T01:53:49.487Z