开发者

Dynamically include external Javascript file

开发者 https://www.devze.com 2023-03-22 23:17 出处:网络
So I need to dynamically call and execute the javascript code generated from external php file. This is what I have:

So I need to dynamically call and execute the javascript code generated from external php file. 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. I tried going through other similar questions on StackOverflow and other places, but that's as far as it got me. 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


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? e.g. 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:

alert('loaded');


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;

Ex:

function needToExecute() {
    ...
}

needToExecute();


Take a look at : http://headjs.com/

0

精彩评论

暂无评论...
验证码 换一张
取 消