<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
document.addEventListener('DOMContentLoaded', () => {
const h1 = (text) => `<h1>${text}</h1>`
document.body.innerHTML += h1('DomContentLoaded event')
})
</script>
</head>
<body>
</body>
</html>
### Key Elements of the Script
- **`DOMContentLoaded` Event Listener**: The script sets up an event listener for the `DOMContentLoaded` event, which fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
- **Arrow Function for Creating `<h1>`**: Inside the event listener, an arrow function `h1` is defined that takes a single parameter `text`. This function returns a string that represents an HTML `<h1>` element with the provided text inserted inside it.
- **Dynamic HTML Update**: The document's `body` content is augmented using the `+=` operator, which appends the string returned by the `h1(text)` function call to the current `innerHTML` of the `<body>` element. In this case, the function is invoked with the argument `'DomContentLoaded event'`, resulting in the addition of `<h1>DomContentLoaded event</h1>` to the body.
### Execution Flow
1. The browser loads the HTML document.
2. Before the `DOMContentLoaded` event fires, the browser prepares the DOM but does not execute the script within the `<script>` tag because it's set to wait for the event.
3. Once the DOM is fully loaded, the `DOMContentLoaded` event fires, triggering the execution of the event listener's callback function.
4. The callback function constructs an `<h1>` element with the text `'DomContentLoaded event'` and appends it to the document's body.
### Implications
- The use of `document.body.innerHTML += ...` effectively adds content to the end of the document's body. However, it's worth noting that using `innerHTML += ...` to modify existing content can lead to inefficient re-parsing of the entire inner HTML content of the target element, potentially removing event listeners from child elements and affecting performance. For adding elements, methods like `document.createElement` and `Node.appendChild` or `Element.insertAdjacentHTML` are generally preferred for their efficiency and finer control over the DOM.
- This script demonstrates a straightforward method for modifying the DOM after ensuring that the entire document is loaded, which is crucial for scripts that need to access or modify elements that may not be immediately available in the document.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
chapter 8) try catch finally (0) | 2024.12.24 |
---|---|
chapter 7) Creating a document object (0) | 2024.12.23 |
chapter 7) handle to javascript code in HTML (1) | 2024.12.21 |
chapter 7) Keyboard event (1) | 2024.12.19 |
chapter 7) localStroage (0) | 2024.12.18 |