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
-
2If that was really what you had, then the div wouldn't show up as the script would error on line one because you forgot the closing quote for the string.Quentin– Quentin2011年07月27日 06:43:35 +00:00Commented Jul 27, 2011 at 6:43
-
Oh no sorry... it was error when I edited to script to post it.Bashar Abdullah– Bashar Abdullah2011年07月27日 09:24:07 +00:00Commented Jul 27, 2011 at 9:24
3 Answers 3
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');
2 Comments
<div id="script"> <script type="text/javascript" src="http://example.com/javascript.php?id=123"> </script> </div> 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();
2 Comments
<div id="script"> <script type="text/javascript" src="http://example.com/javascript.php?id=123"> </script> </div> NOTE: I forgot to mention I am attaching dynamic id to the url. Shouldn't make difference to the javascript call should it? If I run the javascript in separate page, it generates the correct output<script type="text/javascript"> function sayHi() { alert('hi mecca'); } sayHi(); </script>Take a look at : http://headjs.com/