Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to update only the changed innerHTML of the document

I have 2 JS variables. before and after. They contains the SAME html document, but have some modification. About 1%-10% change between them. I want to update the body from before to after. The variablesbefore and after are raw string.

I can do something like that:

document.documentElement.innerHTML=after

The problem is that if I render this way it not look good. The render takes time, and there is a white screen between the renders. I want to show the user 10 modification in a second (video of modifications)

So what I want to do. I want to search and find only the elements that changed only by analyze the HTML text of before and after.

My way of solution:

I can find the changes and the position in the text using Javascript Library for diff & match & patch.

The question is:

After I find the text changes. How to find only the elements who changed. I update only those elements.

I thought, maybe to create a range, that contains every change, and update the range, but how exactly to do that?

If anything unclear, please comment, I will explain better.

like image 816
Aminadav Glickshtein Avatar asked Feb 24 '16 10:02

Aminadav Glickshtein


People also ask

How do I change the content of innerHTML of HTML elements?

To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.

Which element do you use to replace innerHTML?

HTML specifies that a <script> tag inserted with innerHTML should not execute. For that reason, it is recommended that instead of innerHTML you use: Element.SetHTML() to sanitize the text before it is inserted into the DOM.

Is setting innerHTML synchronous?

Setting innerHTML is synchronous, as are most changes you can make to the DOM.

Why you should not use innerHTML in JavaScript?

Can break the document: There is no proper validation provided by innerHTML, so any valid HTML code can be used. This may break the document of JavaScript. Even broken HTML can be used, which may lead to unexpected problems.


1 Answers

I found a very good library for it: https://github.com/patrick-steele-idem/morphdom

Lightweight module for morphing an existing DOM node tree to match a target DOM node tree. It's fast and works with the real DOM—no virtual DOM here!

Very easy to use, and doing exactly what I need

like image 90
Aminadav Glickshtein Avatar answered Sep 20 '22 15:09

Aminadav Glickshtein