对于我的Greasemonkey脚本,在加载页面(@run-at document-start
)之前应该运行部分代码,并且在加载文档之后应该运行代码的另一部分(@run-at document-end
) 。
这可能吗?
我宁愿不使用jQuery。
我尝试了onload
事件,但它没有用。如果文件还没有,我认为不能附上这个活动吗?
window.document.onload = function(e){
alert("document.onload" );
}
答案 0 :(得分:22)
您想要的活动是DOMContentLoaded
。此外,这不是如何使用load
事件。
这是一个完整的脚本,演示了各种触发时间:
// ==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() );
典型结果:
"==> 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