DOM/htmlAsync()

This function sets or gets an element's HTML/XML content. It is the programmatic alternative to Element.innerHTML. Additionally, when this function receives undefined for a set operation, an empty string will be used instead.

The suffix Async differentiates this method from its Sync counterpart - htmlSync(). Unlike the Sync counterpart, htmlAsync() is a promised-based function that runs in a different flow from that of the calling code. It follows a performance strategy that lets the browser engine decide the most convenient time to honour its call.

Import

import htmlAsync from '@web-native-js/play-ui/src/dom/htmlAsync.js';

Syntax

// Method signature
let promise = htmlAsync(el[, content = null]);

> Set Content

let promise = htmlAsync(el, content);

Parameters

  • el - HTMLElement: The target DOM element.

  • content - String|HTMLElement: The content to set. This could be a plain text, an HTML/XML markup, or even a DOM node.

Return

  • Promise - A Promise that resolves when the operation finally gets executed. The target DOM element is returned when the promise resolves.

> Get Content

let promise = htmlAsync(el);

Parameters

  • el - HTMLElement: The source DOM element.

Return

  • Promise - A Promise that resolves when the operation finally gets executed. The source element's content is returned when the promise resolves.

Usage

<body>
<div>DIV1</div>
</body>
// Set content
htmlAsync(document.body, '<main><div>DIV1</div></main>').then(body => {
// Do something with body
});
// Get content
htmlAsync(document.body).then(content => {
// Do something with content
});

Implementation Note

Technically, DOM operations initiated with htmlAsync() are internally batched to an appropriate queue using the Reflow utility. Read operations run first, then write operations. This works to eliminate layout thrashing as discussed in Reflow's documentation.

Notice the order of execution in the following example.

// Set content
htmlAsync(document.body, 'Hi').then(() => {
console.log('Set operation 1');
});
// Get content
htmlAsync(document.body).then(content => {
console.log('Get operation 1');
});
// Set content
htmlAsync(document.body, 'Hi again').then(() => {
console.log('Set operation 2');
});
// Get content
htmlAsync(document.body).then(content => {
console.log('Get operation 2');
});
// ------------
// console
// ------------
Get operation 1
Get operation 2
Set operation 1
Set operation 2

The proper way to synchronize with an async function is to move code into its then() block as seen below.

// Set content
htmlAsync(document.body, 'Hi').then(body => {
console.log('Set operation 1');
// Get content
htmlAsync(body).then(content => {
console.log('Get operation 1');
});
});
// ------------
// console
// ------------
Set operation 1
Get operation 1