简体   繁体   English

如何在不使用DOM突变事件的情况下检测AJAX节点插入?

[英]How can I detect AJAX node insertion without using DOM mutation events?

I'm trying to write a Greasemonkey script that alters keywords in Twitter posts. 我正在尝试编写一个改变Twitter帖子中关键字的Greasemonkey脚本。 Trouble is, the content is "late loading" and is added to at the users request. 麻烦的是,内容是“延迟加载”,并在用户请求时添加。

If I were adding event listeners to the added elements, I could use JQuery's delegate() . 如果我向添加的元素添加事件监听器,我可以使用JQuery的delegate() As I simply want to change the content when it loads, this doesn't appear to be appropriate. 因为我只是想在加载时更改内容,这似乎不合适。

Mutation Events seem to fit the bill. 变异事件似乎符合要求。 They are Gecko specific, but this doesn't matter much for a Greasemonkey script. 它们是Gecko特有的,但这对于Greasemonkey脚本来说并不重要。 Problem is, they have been depreciated and for a set of very good reasons . 问题是, 它们已被折旧并且有一系列非常好的理由

Of course I could use a timer and poll the DOM at regular intervals, but this just seems icky. 当然我可以使用计时器并定期轮询DOM,但这看起来很蹩脚。

How can I detect additions to the DOM and react to the inserted elements? 如何检测DOM的添加内容并对插入的元素做出反应?

If you want to detect AJAX-created nodes your options (besides Mutation events which you are wise to rule out) are: 如果你想检测AJAX创建的节点你的选择(除了你明智要排除的Mutation事件)是:

  1. Polling with an interval or timer. 使用间隔或计时器轮询。
  2. Trying to hook into the page's AJAX requests (if any). 试图挂钩页面的AJAX请求(如果有的话)。
  3. Splicing into, hijacking, or replacing the page's javascript. 拼接,劫持或替换页面的javascript。

I've done all of these at one time and all but one have major drawbacks: 我已经一次完成了所有这些,除了一个以外都有一个主要的缺点:

  1. Splicing into the page's javascript is not always easy (especially with anonymous functions), usually requires complicated deconstruction of that code, and is brittle as heck. 拼接到页面的javascript并不总是很容易(特别是对于匿名函数),通常需要对代码进行复杂的解构,并且很容易。 A page's javascript changes without notice. 页面的javascript更改,恕不另行通知。
  2. Hooking into the page's AJAX requests can sometimes be pretty easy, but transferring the information across the sandbox barrier usually makes it more trouble than it's worth. 挂钩页面的AJAX请求有时候非常简单,但是通过沙盒屏障传输信息通常会使它比它的价值更麻烦。
  3. Polling works darn well in practice, is simple to implement, and usually low cost. 轮询工作在实践中很好,实施起来很简单,而且成本通常很低。

I recommend you use the waitForKeyElements() utility and be done with it. 我建议你使用waitForKeyElements()实用程序并完成它。 It's very easy to use. 它非常易于使用。 For example: 例如:

// ==UserScript==
// @name    Highlight good comments
// @include http://SOME_SITE/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// ==/UserScript==

function highlightGoodComments (jNode) {
    if (/beer/i.test (jNode.text () ) ) {
        jNode.css ("background", "yellow");
    }
}

waitForKeyElements ("#userBlather div.comment", highlightGoodComments);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM