简体   繁体   中英

Dynamically include external Javascript file

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

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 ;

Ex:

function needToExecute() {
    ...
}

needToExecute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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