I got a page that loads several add-ons and I need to insert html element (script) just before body closing tag (</ body>) as last loading. I tried some javascript methods such as appendChild and insertAdjacentElement, but none seem to work because of loading other scripts.
What I have done so far and didn’t work:
Using appendChild or insertAdjacentElement got same result:
var myscript = document.createElement('script');
myscript.setAttribute('src','https://xxxxx/myscript.min.js');
myscript.async = true;
document.body.appendChild(myscript); or document.body.insertAdjacentElement('beforeend', myscript);
Result:
<body>
<element1>
<element2>
*<myscript> <--- inserted here*
<element3>
<element4>
<element5>
<element6>
<element7>
</body>
Expected result:
<body>
<element1>
<element2>
<element3>
<element4>
<element5>
<element6>
<element7>
*<myscript> <--- insert here*
</body>
2
Answers
It looks like the javascript code might be executed before the html document is fully loaded. To avoid this place your javascript code inside a DOMContentLoaded to make sure the code runs after the DOM is fully loaded:
seems to be working for me with append