Adam
Adam

Reputation: 6122

Dynamically include javascript code from within javascript file

I'm inserting the following script, which is on my own server, into an external page of a 3rd party: www.test.com/test.html:

<script type="text/javascript">
(function() {
  var protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
  var ttScript = document.createElement('script');ttScript.async = true;
  ttScript.src = '//www.example.com/script/mycode.js';
  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ttScript);
})();
</script>

This is the other script I want to dynamically inject, please note that it can't just be added to the above script! I want this script to be dynamically available. This complete code, will later be stored within object message.jsScript

<script type="text/javascript">
var tt_totalordervalue;
function tt_getordervalue(){
    tt_totalordervalue=$('#subtotal');
    console.log(tt_totalordervalue);
}
</script>

In file mycode.js:

I want to dynamically add the above script and call the function tt_getordervalue defined in there, I'm now trying to do this as below. Notice that I also want to assign the value of variable tt_totalordervalue which is defined in the dynamic script, to a variable in my mycode.js:

(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(message.jsScript);
console.log('script added');
tt_getordervalue();
console.log('function called');
var val = tt_totalordervalue;

I however then get the error Uncaught NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.

Why?

Upvotes: 0

Views: 104

Answers (1)

Jared Smith
Jared Smith

Reputation: 21926

Following works on chrome on a Mac (sorry, was too lazy to cross test):

var script = document.createElement('script');
script.innerHTML = 'window.doStuff = function(){alert("do")}';
document.getElementsByTagName('body')[0].appendChild(script);
doStuff();

Upvotes: 1

Related Questions