0

I have this JS:

<script type="text/javascript">
var aaascript = document.createElement('script'); aaascript.type = 'text/javascript';
aaascript.src = ('https:' == document.location.protocol ? 'https://xxx' : 'http://xxx') + '/aaa.js';
var aaas = document.getElementsByTagName('script')[0]; aaas.parentNode.insertBefore(aaascript,aaas);
callthis('somevalue');
</script>

this code generates a script tag and inserts it to the page. in the script aaa.js is the function callthis. but when I call the function there is this error:

Uncaught ReferenceError: callthis is not defined (anonymous function)

what goes wrong here?

4
  • 1
    Most probably due to the fact that you are loading it at runtime via javascript it is not being parsed ergo you do not have the methods available. Needs some testing though. Are you receiving any errors whatsoever or are there any variables in there that are available? Consider using this stackoverflow.com/questions/3261408/… instead if possible. Commented Oct 4, 2013 at 8:26
  • no there are no other errors. I cant use jquery in this case, need plain js Commented Oct 4, 2013 at 8:30
  • Simon has a point, that might be what you are looking for. Commented Oct 4, 2013 at 8:31
  • I realise you're not after a jQuery solution but for others' reference: the getscript or ajax methods Alex linked to can be used to load the script. Using your example, you would still need to delay calling callthis() until the script is loaded, by wrapping it in a function and putting it in the success parameter of those jQuery methods. Commented Oct 4, 2013 at 8:36

1 Answer 1

2

The script tag is being created but the script is then loaded from the server. callthis() is being called in between these two events; that is, before the script is fully loaded, and so the method doesn't exist.

Use the .onload event of the script tag to delay calling callthis() until the script is fully loaded, as documented here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.