为了账号安全,请及时绑定邮箱和手机立即绑定

请问document.createElement(“脚本”)同步

请问document.createElement(“脚本”)同步

梵蒂冈之花 2019-10-22 17:12:04
document.createElement(“脚本”)同步可以打电话给.js同步归档,然后立即使用它?<script type="text/javascript">     var head = document.getElementsByTagName('head').item(0);     var script = document.createElement('script');     script.setAttribute('type', 'text/javascript');     script.setAttribute('src', 'http://mysite/my.js');     head.appendChild(script);     myFunction(); // Fails because it hasn't loaded from my.js yet.     window.onload = function() {         // Works most of the time but not all of the time.         // Especially if my.js injects another script that contains myFunction().         myFunction();     };</script>这很简单。在我的实现中,createElement在一个函数中。我考虑在函数中添加一些内容,以便在返回控件之前检查某个变量是否被实例化。但是,当包含来自另一个我无法控制的站点的js时,仍然存在着如何处理的问题。思想?编辑:我已经接受了最好的答案,因为它给出了一个很好的解释所发生的事情。但是如果有人对如何改进这个问题有任何建议的话,我对他们是开放的。这是我想做的事情的一个例子。// Include() is a custom function to import js.Include('my1.js');Include('my2.js');myFunc1('blarg');myFunc2('bleet');我只是不想太多地了解内部结构,只想说:“我希望使用这个模块,现在我将使用它中的一些代码。
查看完整描述

3 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

这不是很漂亮,但效果很好:

<script type="text/javascript">
  document.write('<script type="text/javascript" src="other.js"></script>');</script><script type="text/javascript">
  functionFromOther();</script>

<script type="text/javascript">
  document.write('<script type="text/javascript" src="other.js"></script>');
  window.onload = function() {
    functionFromOther();
  };</script>

脚本必须包含在单独的<script>标签或之前window.onload().

这是行不通的:

<script type="text/javascript">
  document.write('<script type="text/javascript" src="other.js"></script>');
  functionFromOther(); // Error</script>

创建节点也可以这样做,就像SPINTY一样,但只能在FF中进行。您无法保证脚本何时会在其他浏览器中准备就绪。

作为一个XML纯粹主义者,我真的很讨厌这一点。但它确实可以预期地发挥作用。你可以轻易地把那些丑陋的东西包起来document.write()这样你就不用看他们了。您甚至可以进行测试并创建一个节点并将其追加到document.write().



查看完整回答
反对 回复 2019-10-23
  • 3 回答
  • 0 关注
  • 317 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信