英文:
How to insert html element just before body closing tag as last loading
问题
我有一个加载了多个附加组件的页面,我需要在</body>
标签关闭之前作为最后加载的内容插入HTML元素(脚本)。我尝试了一些JavaScript方法,如appendChild
和insertAdjacentElement
,但似乎都无法正常工作,因为还有其他脚本在加载。
到目前为止我尝试但未成功的方法:
使用appendChild
或insertAdjacentElement
获得相同的结果:
var myscript = document.createElement('script');
myscript.setAttribute('src', 'https://xxxxx/myscript.min.js');
myscript.async = true;
document.body.appendChild(myscript); 或 document.body.insertAdjacentElement('beforeend', myscript);
结果:
<body>
<element1>
<element2>
*<myscript> <--- 在此处插入*
<element3>
<element4>
<element5>
<element6>
<element7>
</body>
期望的结果:
<body>
<element1>
<element2>
<element3>
<element4>
<element5>
<element6>
<element7>
*<myscript> <--- 在此处插入*
</body>
英文:
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>
答案1
得分: 1
看起来 JavaScript 代码可能在 HTML 文档完全加载之前执行。为了避免这种情况,将你的 JavaScript 代码放在 DOMContentLoaded 事件内,以确保代码在 DOM 完全加载后运行:
document.addEventListener('DOMContentLoaded', function() {
var myscript = document.createElement('script');
myscript.setAttribute('src','https://xxxxx/myscript.min.js');
myscript.async = true;
document.body.appendChild(myscript);
});
英文:
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:
document.addEventListener('DOMContentLoaded', function() {
var myscript = document.createElement('myscript');
myscript.setAttribute('src','https://xxxxx/myscript.min.js');
myscript.async = true;
document.body.appendChild(myscript);
});
答案2
得分: 0
似乎对我有用,使用append
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论