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

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

问题描述

我正在尝试编写一个 Greasemonkey 脚本来更改 Twitter 帖子中的关键字.问题是,内容延迟加载"并应用户要求添加.

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 的 delegate().因为我只是想在加载时更改内容,所以这似乎不合适.

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天全站免登陆