在 DOM 中动态插入脚本

发布于 2024-11-30 06:58:48 字数 487 浏览 1 评论 0原文

我试图理解为什么这段代码不起作用并且警报输出只是空白。

<script type="text/javascript">
(function() {
  ... 
  var s = document.getElementsByTagName('script')[0]; alert(s.innerHTML);       
  s.parentNode.insertBefore(res, s);
  ... 
})();
</script>

如果我没记错的话,应该在 s 之前添加 res 。这就是我特别需要的,因为我尝试将其附加到正文并成功添加(在这样做之后,尽管我必须在此函数内运行一些代码,所以如果脚本没有在它之前加载,这样的代码会出错)。

该函数应该在加载文档时运行,或者这是问题所在?特别是,getElementsByTagName函数似乎没有返回任何内容。

谢谢大家。

I'm trying to understand why this code doesn't work and the alert output is just blank.

<script type="text/javascript">
(function() {
  ... 
  var s = document.getElementsByTagName('script')[0]; alert(s.innerHTML);       
  s.parentNode.insertBefore(res, s);
  ... 
})();
</script>

It should add res before s if I'm not wrong. That's what I specifically need, as I tried to append it to body and it's added successfully (after doing that though I have to run some code inside this function, so if the script is not loaded before it, such code will error).

This function should run when document is loaded or is that the problem? In particular, the getElementsByTagName function seems to not return anything.

Thanks to everyone.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

长亭外,古道边 2024-12-07 06:58:48

在加载文档之前您无法运行此类代码。必须先加载此代码,然后才能运行(请参阅此处的循环参数)。到那时,文档的其余大部分内容都已加载。您可以在加载文档后动态加载脚本。如果您需要在其他脚本之前加载脚本,那么您要么必须按照需要运行的顺序将它们全部静态地放入文档中,要么需要按照需要运行的顺序动态添加它们,然后您将需要在加载下一个负载之前跟踪一个负载的完成情况。

如果您愿意描述您想要解决的更广泛的问题,我们可能会建议一个比您所追求的更优雅的解决方案。

You cannot run this type of code before the document is loaded. This code has to be loaded before it can be run (see the circular argument here). And, by then, much of the rest of the document has been loaded. You can dynamically load scripts AFTER the document has been loaded. If you need a script loaded before other scripts, then you either have to put them all in the document statically in the order you need them to be run or you need to add them all dynamically in the order you need them to run and you will need to keep track of completion of one load before loading the next.

If you care to describe the broader problem you're trying to solve, we can probably suggest a more elegant solution than what you are pursuing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文