For example, if I update innerHTML of a div after an AJAX call, how does the browser know that it's time to refresh/repaint the UI?
document.getElementById('someid').innerHTML = response.responseJSON.text;
In this case as soon as innerHTML is set, the change is visible on the UI. How exactly does it happen?
The thing is, the browser and the JS API you are using are directly wired. Where do you think the document and window come from? Why are they not in Node.JS? I think, it's easy to explain using Node.JS's VM module:
The VM module lets you run a script in a separated container, a sandbox, or however you'd like to call it. A similar functionality is exposed by JS interpreter libraries, like Google's V8, to lower-level programmers (in C++).
const vm = require('vm');
The initial global scope is empty. There is no JSON, there is no window, there is no document, there is no setTimeout, there is no nothing. In JS-terms, it would look like {}, not counting standard object methods and properties. So they add functions and objects with methods, implement them and, that way, can wire the render code directly to whatever you might write. A very simplistic example might look like the following snipped, with pseudo-code, entirely implemented in JS (normally it would happen in C++) for your convenience:
const sandbox = {
document: {
getElementById: function(id) {
// find element and return it as a new object
return {
// The following line is a setter: developer.mozilla.org/en-US/docs/Web/JavaScript/R…
set innerHTML(html) {
// repaint website
},
// various other properties
};
},
},
// various other functions and objects
};
const context = new vm.createContext(sandbox);
const script = new vm.Script(youJSFileHere);
// and execute some JS file you included in your HTML
script.runInContext(context);
This article may be of use. It explains how browsers work and goes through the entire process from start to finish :)
sai did a story about the virtual dom where he posted a video about the dom rendering engines :)
here is a diagram
Sai Kishore Komanduri
Engineering an eGovernance Product | Hashnode Alumnus | I love pixel art
The article shared by @hipkiss91 is indeed an excellent resource to get a better understanding of how browsers work under the hood.
Thank you for sharing the link, @chilimatic. The diagram he is referring to is this one, the workflow of a browser's rendering engine:
Here is an excerpt from the How Browsers Work article, that answers your particular question:
So in your case, here is a very high-level overview of what exactly happens — as soon as you change the
innerHTMLattribute; the DOM tree is updated, and further along the flow, styles are attached to the node, creating a render object; which would be replaced with the corresponding old node in the Render Tree. Whenever there is a change, the render tree is traversed, and for all the visible render objects, their correspondingpaintmethods are called.