I have the following Javascript function which intends to load HTML and execute a callback function once the HTML has been loaded.
I would like to clarify if adding text to innerHTML guarantees that the elements will be available in the DOM.
Is the callback function called after all the elements loaded are ready in the DOM in this case or it might be the case it is not?
function loadView(viewId, callback) {
let contentDiv = document.getElementById('content');
let url = `${viewId}.html`; // Correctly construct the URL using template literals
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
// Append the fetched content to contentDiv
contentDiv.innerHTML += data;
// Invoke the callback
if (typeof callback === 'function') {
callback();
}
})
.catch(error => {
console.error('Error loading content:', error);
});
}