Frontend Development: What is DOM, Shadow DOM, and Virtual DOM?

Peter Jeon·2023년 6월 19일
0

Frontend Development

목록 보기
13/80
post-custom-banner

Frontend Development

In this blog post, we will be discussing three key concepts in frontend development: DOM, Shadow DOM, and Virtual DOM. Understanding these concepts is crucial for every frontend developer.

What is DOM?

DOM

The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a web document and can be manipulated to change the document content, structure, and style.

When a web page is loaded, the browser creates a DOM of the page, which is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript.

// Accessing DOM element
let element = document.getElementById("myDiv");

// Manipulating DOM element
element.style.color = "blue";

What is Shadow DOM?

Shadow DOM is a web standard that offers encapsulation for JavaScript, CSS, and templating in the DOM. It allows for functionally and style encapsulation - everything inside the Shadow DOM is separate from the main DOM tree, which can simplify the styling and scripting of complex components.

javascript
// Creating a shadow root
let shadow = element.attachShadow({mode: 'open'});

// Adding new element to shadow DOM
let paragraph = document.createElement("p");
paragraph.textContent = "Hello from the Shadow DOM";
shadow.appendChild(paragraph);

What is Virtual DOM?

Virtual DOM is a concept where a virtual representation of the actual DOM is kept in memory and synced with the real DOM by libraries such as ReactDOM. This process is called reconciliation.

The Virtual DOM is an abstraction of the HTML DOM, and it is lightweight and detached from the browser-specific implementation details. It allows React to do its computations within this abstract world and skip the "real" DOM operations, often speeding up the updates.

// React component utilizing Virtual DOM
class MyComponent extends React.Component {
  render() {
    return <h1>Hello world</h1>;
  }
}

Comparison

DOMShadow DOMVirtual DOM
EncapsulationNoYesYes
Browser SupportAllModern BrowsersAll (with React)
Use CaseGeneral PurposeWeb ComponentsReact Apps

Understanding these different DOM models is a key step in mastering modern frontend development and will give you the tools to create efficient and performant web applications.

profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

0개의 댓글