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?
innerHTMLwith the desired code to be run. Its still going to wind up in the global scope though.Uncaught TypeError: string is not a functionon the line where I try to set the innerHTML... And I want it to be in the global scope so that the variables I declare in that script are available everywhere (mainly inmycode.js)Uncaught ReferenceError: tt_getordervalue is not definedI also don't see the script anywhere when I view page source or inspect the page (not sure if I should).