两个 HTML 块之间的差异:结构而不是行/字符?

发布于 2024-11-29 11:32:23 字数 432 浏览 2 评论 0原文

我正在寻找一个 JavaScript diff 引擎,它将返回两个 HTML 块的结构差异。也就是说,不是“在这一行,在这样那样的字符处,发生了一些事情”,而是“这个元素被插入到这个元素之后”,或者“这个元素被删除”,或者“这个文本节点被删除”。粗略

的研究表明这很难

具体场景是我有 Markdown 文本编辑器的实时预览。它仅适用于文本,但一旦用户在 YouTube 嵌入中发帖,它就会在每次击键时呈现/重新加载,这是非常昂贵的。大图像也很困难,因为它们从缓存加载时会产生令人作呕的抖动效果(至少在 WebKit 中)。

漂亮的是 jQuery.html() 的替代品,它不只是替换 HTML 内容,实际上将新旧内容进行比较,并有选择地更新/插入/附加,以便保留未更改的元素。

I'm looking for a JavaScript diff engine that will return the difference in the structure of two chunks of HTML. That is, instead of, "at this line, at such and such character, something happened", it'd be, "this element was inserted after this element", or "this element was removed", or "this text node was altered", etc.

Cursory research suggests this is hard.

The specific scenario is that I have a live preview of Markdown text editor. It works well with just text, but as soon as a user posts in, say, a YouTube <iframe> embed, then it renders/reloads on every keystroke, which is absurdly expensive. Large images are difficult, too, because they cause a nauseous jittering effect as they load from the cache (at least in WebKit).

What would be beautiful is a replacement for jQuery.html() that instead of just replacing the HTML contents actually compared the old with the new, and selectively updated/inserted/appended so that unchanged elements are left alone.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你在我安 2024-12-06 11:32:23
  1. 深度克隆(通过 node.cloneNode(true))当前正在使用的两个节点(即,如果 JavaScript 中引用了任何子节点)。
  2. 通过node.normalize()标准化两个节点。
  3. 迭代两个节点的每个子节点并与 node.isEqualNode(other_node) 进行比较。
  4. 对于每个不相等的节点,深入迭代以查看是否可以找到任何相等的子节点。

老实说,使用文本比较库比创建自己的基于 DOM 的比较库要好得多。

  1. Deep clone (via node.cloneNode(true)) both nodes if they're currently in use (i.e. if any child nodes are referenced in your JavaScript).
  2. Normalize both nodes via node.normalize().
  3. Iterate over every child node of both nodes and compare with node.isEqualNode(other_node).
  4. For every non-equal node, iterate deeper to see if you can find any equal child nodes.

To be honest, you're much better off using a text diff lib instead of making your own DOM-based diff lib.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文