×

油猴@runat在多个事件中使用的方法

2021-03-07 11:17:04 Falcon

@runat 在油猴脚本可以设置值为 document-start , document-body , document-end 等,表示脚本在网页生命周期的注入点,但是在不同生命周期运行多个不同的事件呢?参考stackoverflow的答案:

// ==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

参考:https://stackoverflow.com/q/12045440/3258851

本文收录于