Reputation: 931
For example,
const elem = document.getElementById('myElem')
elem.style.height = '300px'
How does js engine detect that the elem
has been changed and triggers the repaint of the document?
Context
This question came to my mind because I am working with angular and when changing variables related to the view from the controller, the change detection gets triggered and the view is updated. Therefore, I want to know if there is any strategy to detect changes in the js engine that is activated when we update DOM through the DOM API. Thanks
Upvotes: 0
Views: 107
Reputation: 3845
It uses the MutationObserver to monitor changes to the DOM. From the documentation:
The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3 Events specification.
This article also provides a good overview of how this is achieved, with some code samples.
Here is a code sample from the documentation showing how the engine observes the DOM for changes. You can modify this to suit your case.
// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
Upvotes: 2
Reputation: 51876
The style
property is an instance of the CSSStyleDeclaration
class, which makes use of the same internal logic when either setProperty()
is called or when a value is assigned to one of its CSS declaration properties.
The vendor can then implement the internal logic however they need to in order to schedule repainting and other dependent behavior, as long as they conform to the constraints enumerated in the specification, which only suggests one possible implementation for the internal logic.
Upvotes: 1