如何在不使用DOM突变事件的情况下检测AJAX节点插入? [英] How can I detect AJAX node insertion without using DOM mutation events?

查看:211
本文介绍了如何在不使用DOM突变事件的情况下检测AJAX节点插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个改变Twitter帖子中关键字的Greasemonkey脚本。麻烦的是,内容是延迟加载,并在用户请求时添加。

I'm trying to write a Greasemonkey script that alters keywords in Twitter posts. Trouble is, the content is "late loading" and is added to at the users request.

如果我在添加的元素中添加事件监听器,我可以使用JQuery的委托()。由于我只是想在加载时更改内容,这似乎不合适。

If I were adding event listeners to the added elements, I could use JQuery's delegate(). As I simply want to change the content when it loads, this doesn't appear to be appropriate.

突变事件似乎符合要求。它们是Gecko特有的,但这对于Greasemonkey脚本来说并不重要。问题是,它们已被折旧和一组非常好的理由

Mutation Events seem to fit the bill. They are Gecko specific, but this doesn't matter much for a Greasemonkey script. Problem is, they have been depreciated and for a set of very good reasons.

当然我可以使用计时器并定期轮询DOM,但这看起来很蠢。

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?

推荐答案

如果你想检测AJAX创建的节点你的选择(除了你明智要排除的Mutation事件)是:

If you want to detect AJAX-created nodes your options (besides Mutation events which you are wise to rule out) are:


  1. 使用间隔或计时器进行轮询。

  2. 尝试挂钩页面的AJAX请求(如果有的话)。

  3. 拼接,劫持或替换页面的javascript。

我已经完成了所有这些,但除了一个之外都有一个主要的缺点:

I've done all of these at one time and all but one have major drawbacks:


  1. 拼接到页面javascript并不总是那么简单(特别是对于匿名函数),通常需要对代码进行复杂的解构,并且很容易。页面的javascript会在没有通知的情况下发生变化。

  2. 挂钩页面的AJAX请求有时候非常简单,但是通过沙箱屏障传输信息通常会使它比它的价值更麻烦。

  3. 投票工作在实践中很好,实施起来很简单,而且成本通常很低。

我建议您使用 waitForKeyElements()实用程序并完成它。
这很容易使用。例如:

I recommend you use the waitForKeyElements() utility and be done with it. 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);

这篇关于如何在不使用DOM突变事件的情况下检测AJAX节点插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆