2014-10-09 25 views
8

對於我的Greasemonkey腳本,應該在加載頁面之前運行一部分代碼(@run-at document-start),並在加載文檔之後運行另一部分代碼(@run-at document-end)。
這可能嗎?腳本運行 如何讓Greasemonkey腳本在@ run-at document-start和at @ run-at文檔結束時運行?

  • 頁面加載的

    • 第1部分,文件準備腳本運行的
    • 第二部分

    我寧可不使用jQuery這一點。

    我試過onload事件,但沒有奏效。我認爲如果文件不在那裏,則不能附加事件?

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

    15

    想要的事件是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