Suppose that get a DOM as reference Node, then create and insert a DOM as new Node.
If I create and insert the new Node as soon as possible, is DOMContentLoaded the best event option in the above situation?
The reference Node is not image, it's HTMLnknowElement such as a HTMLDivElement, HTMLSpanElement.
Here is an example code flow.
window.addEventListener("DOMContentLoaded", (event) => {
// Below is an example code as pseudo code.
// Get a reference DOM.
const referenceEl = document.querySelector(".foo .reference-dom");
// Create a new DOM.
const newEl = document.createElement(htmlTag);
// Insert the new DOM before reference DOM.
referenceEl.parentElement.insertBefore(newEl, referenceEl.nextElementSibling)
})
If I execute the code as soon as possible, is DOMContentLoaded the best event option in the above situation?
CodePudding user response:
If you want the code to run as soon as possible, given what elements it depends on already existing in the DOM, the easiest way to do it would be to put your <script>
tag just below the final element required for the script to run. For example, for the .reference-dom
, you might do
<div >
...
</div>
<script>
const referenceEl = document.querySelector(".foo .reference-dom");
// or
const referenceEl = document.currentScript.previousElementSibling;
// ... etc
If that's not an option, another avenue available to you would be to add a subtree MutationObserver to the document ahead of time (such as at the beginning of the <body>
, and to watch the addedNodes
to see if the node you're looking for appears - but that's expensive, overkill, and much more difficult to manage.
For very large pages (example), waiting for DOMContentLoaded could indeed take too long, in which case what you're doing would be a good idea - to add essential functionality to the app before that event fires, to ensure a good user experience. (Though, if what you're doing is just adding another tag to the HTML, a better approach would be to use a template engine or something server-side so that it serves the full HTML itself, rather than having to alter it client-side through JavaScript later)