在jQuery中使用$(document).ready的Greasemonkey问题

der*_*ek8 1 jquery greasemonkey loading document-ready

当我访问www.reuters.com时,我无法弄清楚为什么这至少不会提醒我一次.我错过了什么吗?

// ==UserScript==
// @name        test3
// @namespace   test3
// @version     1
// ==/UserScript==

$(document).ready(function () {

    var actualHost = window.location.toString();
    var intendedHost = "www.reuters.com";

    alert("Debug 1 - " + actualHost);

    if (actualHost == intendedHost) {
        alert("Debug 2 - " + actualHost);
    }

});
Run Code Online (Sandbox Code Playgroud)

谢谢.

Bro*_*ams 7

  1. 为了使用jQuery,您必须加载jQuery.
  2. $(document).ready()大多数Greasemonkey脚本都不需要,因为默认情况下Greasemonkey会在适当的时间触发.

因此最简单的脚本版本变为:

// ==UserScript==
// @name     test3
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

var actualHost = window.location.toString();
var intendedHost = "www.reuters.com";

alert("Debug 1 - " + actualHost);

if (actualHost == intendedHost) {
    alert("Debug 2 - " + actualHost);
}
Run Code Online (Sandbox Code Playgroud)

注意:

  1. @require尽可能使用(几乎总是如此).

    1. @require 将脚本的副本放在本地计算机上,因此您的脚本运行速度更快,并且不依赖于每次运行的外部服务器.
    2. @require 维护沙箱安全/分离,因此您的脚本可以避免来自目标页面的副作用或攻击
    3. @require 即使你已经禁用了所有目标页面的javascript,你的脚本仍然可以运行 - 这是一种非常有价值的技术.
    4. @require如果你使用优秀的Tampermonkey扩展,甚至可以移植到Chrome .



    其他,复杂的添加jQuery的方法有很多问题:

    1. 它们是不必要的安全风险.
    2. 它们使您的脚本不必要地依赖于每次运行的外部服务器!
    3. 他们减慢你的脚本速度.
    4. 他们使用GM的优秀功能,如GM_xmlhttpRequest()和GM_setValue(),不可能或更难.
    5. 他们将您的脚本绑定到目标页面JS执行的变幻莫测.


  2. 始终为您的脚本提供适当的@include,@exclude和/或@match指令,以便它只在所需的页面上运行.

  3. 考虑使用console.log()而不是alert().它对调试的干扰要小得多.