Introduction
Few weeks back, I had a task to create an online code editor for HTML, CSS, JS and show the output on the same screen.
Why I needed in-memory DOM?
I stored different codes in different variables and for showing the output on same screen, I had to create a virtual DOM and merge all the codes (HTML + CSS + JS) together and inject it into an iframe.
Code
The above code takes HTML, CSS and Javascript as string and then combines them together in HTML. It returns the merged code as a string then it is injected into an iframe.
Demo
You can see the working of the above code in this app.
Web Code Editor
Edit 1.
Changed the title from VDOM to in-memory DOM, as I mistook it for a VDOM.
Thanks @lukeshiru for the suggestion.
Top comments (5)
A Virtual DOM is a lightweight representation of the DOM, not an actual DOM in memory. This isn't a Virtual DOM. Also, you can simplify the implementation drastically by just using a
template
element with some slots for your html, css and JS. Ideally you should render the output of that template in aniframe
without any access to the parent, to make it safer.Edit: I went into the editor and quickly found the security concerns I had were founded. If you select
Javascript
and then write something like this:The app freezes completely. Adding to that, because the code is saved to
localStorage
, then I can't use the app again until I clear that, because every time I open the URL the code runs again and blocks the main thread.I shouldn't be able to access
globalThis
from the generated code, because you can even do stuff like this:And basically loose all your progress.
Thanks for pointing out the bug. Will sort it out soon.
Please do read this article.
reactkungfu.com/2015/10/the-differ...
I already know the difference between a DOM and a virtual DOM. This is not a VDOM:
Is just DOM in memory. The idea with a VDOM is that it is a lightweight representation of the DOM, not the DOM itself. So the example above should look more like this:
I know putting "Virtual DOM" in the title makes the article more attractive, but this isn't a VDOM implementation.
Got it, will change the title.
Thanks for sharing.