2

我在使用@run-at document-start指令时遇到问题。我敢肯定这归结为缺乏经验,但对于我的生活,我无法弄清楚这一点。

除了一些其他指令,这是整个脚本。

// @require https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js  
// @run-at  document-start

FF中的错误

Error: document.documentElement is null  
Source File: file:///C:/Users/---/Test-1/jquery.js  
Line: 4899

我看到并理解了这个问题,我只是不确定要采取什么步骤来让我的脚本尽可能接近文档开始运行,但@required脚本仍然可以正常运行。
对我的第一篇文章有​​点紧张......请放轻松:)

火狐 12
Greasemonkey 0.9.20

4

1 回答 1

1

是的,这是使用// @run-at document-start. @required试图操纵 DOM 的脚本可能会抛出错误。(但许多@required库都很好,因为它们只是加载稍后由您的代码激活的工具)。

您可以使用 、 和监视 来解决@resourceeval()问题readyState。像这样:

// ==UserScript==
// @name        _Using DOM-manipulating libraries with run-at start
// @include     http://YOUR_SERVER/YOUR_PATH/*
// @run-at      document-start
// @resource    jQ_src https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js
// ==/UserScript==

var jQ_src  = GM_getResourceText ("jQ_src");

window.addEventListener ("readystatechange", FireWhenReady, true);

function FireWhenReady () {
    this.fired  = this.fired || false;

    if (    document.readyState != "uninitialized"
        &&  document.readyState != "loading"
        &&  ! this.fired
    ) {
        this.fired = true;
        eval (jQ_src);
        $(document).ready (DoStuff);
    }
}

function DoStuff () {
    //--- Where this next paragraph appears can give you an idea of the delays involved...
    $("body").append ('<p style="background:yellow;">Hello from quick-start jQuery!</p>');
}

重要的!对于像 jQuery 这样的库,使用 没有多大意义@run-at document-start,因为 jQuery 无论如何都不会让你做任何事情$(document).ready(),这是 Greasemonkey 默认触发的时候。

提前加载 jQuery 对您没有任何好处,因为您必须显式使用$(document).ready()(或一种快捷方式)。您可能有其他使用 jQuery 的原因@run-at document-start,也许以后还想使用 jQuery。

于 2012-05-17T01:27:04.510 回答