I'm looking for fragments of HTML
with fetch()
and adding to DOM
with function insertAdjacentHTML()
in loop for()
... the function that performs this task is in Promise()
and its% return (in case of success) use another function to modify the content of parts of the document that contain a certain attribute.
The following example is true:
let fragments = [
{
file: "navbar.html",
mode: "prepend",
target: "#body"
},
{
file: "modal-cookies.html",
mode: "insertAfter",
target: ".drawer-menu"
},
{
file: "footer.html",
mode: "append",
target: "#body"
}
]
//
const __DEFINE__ = () => {
return new Promise((resolve, reject) => {
let urls = [],
param = [],
len = fragments.length
for (let i = 0; i < len; i++) {
urls.push(fragments[i].file);
param.push({
mode: fragments[i].mode,
target: fragments[i].target
})
}
let fetchResource = (url, i) => {
return fetch(url).then(response => {
if ( response.ok ) {
return response.text()
}
return Promise.reject()
}).then(text => {
return text
}).catch(e => {
return Promise.reject(e)
})
}
Promise.all(urls.map(fetchResource)).then(response => {
for (let i = 0; i < response.length; i++) {
let target = document.querySelector(param[i].target)
switch (param[i].mode) {
case 'insertBefore':
target.insertAdjacentHTML('beforebegin', response[i])
break
case 'insertAfter':
target.insertAdjacentHTML('afterend', response[i])
break
case 'append':
target.insertAdjacentHTML('beforeend', response[i])
break
case 'prepend':
target.insertAdjacentHTML('afterbegin', response[i])
break
}
}
// após processar o loop "resolver"
resolve()
}).catch(e => {
reject(e)
})
})
}
//
__DEFINE__().then(() => {
// manipular o DOM após ter adicionado novos Node's
let allTargets = document.querySelectorAll('.uma-classe')
[...allTargets].forEach(item => {
//
item.innerHTML = 'Exemplo'
})
}).catch(e => {
console.error(e)
})
Apparently the loop was processed and new "Node's" were added to DOM
bad when running the function that modified parts of these new elements sometimes when loading the page "it seems" that the "Node's" did not finish being accommodated to the DOM
and consequently the changes are not performed.
Within Promisse.all()
how would you check if these "Node's" were completely added to DOM
?