Engineering note · Javascript

Efficiently Append Multiple Elements

By Published Updated

Javascript

Appending multiple elements to the DOM can be inefficient if done individually.

Use a document fragment to batch append operations.

CODE SAMPLE Code snippet
const fragment = document.createDocumentFragment();
const container = document.getElementById('container');

for (let i = 0; i < 5; i++) {
    const newElement = document.createElement('div');
    newElement.textContent = `Item ${i + 1}`;
    fragment.appendChild(newElement);
}

container.appendChild(fragment);

/*
  This can be useful specially when dynamically you have to append content on web page.
*/

A Document Fragment is a lightweight container used to hold and manipulate a set of DOM elements before appending them to the main document.

It improves performance by minimizing the work the browser has to do when updating the webpage layout and appearance, which helps make page updates faster and smoother.

More engineering notes

Inject a Script into Document Head or Body Tags

You can inject js script into the document head dynamically like this : ``` const basicScript = do...

Dynamically Update Attribute Values

To change the attributes of multiple elements based on user input or other dynamic conditions. Use ~...