Is it possible to call in a .js file synchronously and then use it immediately afterward?
<script type="text/javascript"> var head = document.getElementsByTagName('head').item(0); var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.setAttribute('src', 'http://mysite/my.js'); head.appendChild(script); myFunction(); // Fails because it hasn't loaded from my.js yet. window.onload = function() { // Works most of the time but not all of the time. // Especially if my.js injects another script that contains myFunction(). myFunction(); }; </script> This is simplified. In my implementation the createElement stuff is in a function. I thought about adding something to the function that could check to see if a certain variable was instantiated before returning control. But then there is still the problem of what to do when including js from another site that I have no control over.
Thoughts?
Edit:
I've accepted the best answer for now because it gives a good explanation for what's going on. But if anyone has any suggestions for how to improve this I'm open to them. Here's an example of what I'd like to do.
// Include() is a custom function to import js. Include('my1.js'); Include('my2.js'); myFunc1('blarg'); myFunc2('bleet'); I just want to keep from having to know the internals too much and just be able to say, "I wish to use this module, and now I will use some code from it."
eval()every file in the order given, otherwise just store the response).