【问题标题】:How to get a Greasemonkey script to run both at @run-at document-start AND at @run-at document-end?如何让 Greasemonkey 脚本同时在 @run-at document-start 和 @run-at document-end 运行?
【发布时间】:2014-12-03 19:36:09
【问题描述】:

对于我的 Greasemonkey 脚本,有一部分代码应该在页面加载之前运行 (@run-at document-start),而另一部分代码应该在加载文档之后运行 (@run-at document-end)。
这可能吗?

  • 脚本运行的第一部分
  • 页面已加载,文档已准备就绪
  • 脚本运行的第二部分

我宁愿不使用 jQuery。

我尝试了onload 事件,但没有成功。如果文档还没有,我认为无法附加事件?

window.document.onload = function(e){ 
    alert("document.onload" ); 
}

【问题讨论】:

    标签: javascript greasemonkey startup


    【解决方案1】:

    您想要的事件是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
    
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    相关资源
    最近更新 更多