简体   繁体   English

动态包含外部Javascript文件

[英]Dynamically include external Javascript file

So I need to dynamically call and execute the javascript code generated from external php file. 因此,我需要动态调用并执行从外部php文件生成的javascript代码。 This is what I have: 这就是我所拥有的:

<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>

Now the div with the javascript link does show up, but it doesn't seem to execute. 现在带有javascript链接的div确实出现了,但是似乎没有执行。 I tried going through other similar questions on StackOverflow and other places, but that's as far as it got me. 我尝试过在StackOverflow和其他地方进行其他类似的问题,但就我所知。 Any idea why it's not executing? 知道为什么它没有执行吗?

UPDATE: Fixed the missing quote. 更新:修复了缺少的报价。 Also I should've mentioned I placed the code inside the body. 我还应该提到我将代码放在体内。 I don't have access to the HEAD in my case, and I need to insert the Analytics code 在我的情况下,我无权访问HEAD,我需要插入Google Analytics(分析)代码

The code should cause the code in the script element to be executed (once the missing quote on line 1 is added), are you sure that's exactly what you have in your page? 该代码应导致执行script元素中的代码(一旦在第1行上添加了缺少的引号),您确定这正是页面中的内容吗? eg the following works: 例如以下作品:

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

in _foo.js : _foo.js

alert('loaded');

看看: http : //headjs.com/

After fixing mistakes (such as missing function declaration, closing quote in your code), make sure your code_url reference to a page which has a function calling or an event ; 修正错误(例如,缺少函数声明,代码中的引号)之后,请确保您对具有函数调用事件的页面的code_url引用;

Ex: 例如:

function needToExecute() {
    ...
}

needToExecute();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM