动态包含外部Javascript文件

时间:2011-07-27 06:38:14

标签: javascript

所以我需要动态调用并执行从外部php文件生成的javascript代码。这就是我所拥有的:

<script type="text/javascript">
id = <some id calculation>;
var code_url = 'http://example.com/javascript.php?id=' + id; // this generates the javascript desired

var code_div = document.getElementById("code_div"); // where I want to insert the JS
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", code_url);
code_div.appendChild(fileref);
}
</script>

现在带有javascript链接的div确实显示,但它似乎没有执行。我尝试在StackOverflow和其他地方浏览其他类似的问题,但这就是它让我感觉到的。知道为什么它没有执行吗?

更新:修正了缺失的报价。另外我应该提到我将代码放在体内。在我的情况下,我无法访问HEAD,我需要插入Google Analytics代码

3 个答案:

答案 0 :(得分:3)

代码应该导致脚本元素中的代码被执行(一旦添加了第1行中缺少的引号),你确定这正是你页面中的内容吗?例如以下作品:

window.onload = function() {
  var s = document.createElement('script');
  s.type = 'text/javascript';
  s.src = '_foo.js';
  document.body.appendChild(s);
}
_foo.js中的

alert('loaded');

答案 1 :(得分:2)

答案 2 :(得分:2)

在修正错误(例如缺少功能声明,关闭代码中的引号)后,请确保code_url引用具有函数调用事件的页面

例如:

function needToExecute() {
    ...
}

needToExecute();