Note that there are some explanatory texts on larger screens.

plurals
  1. POdocument.createElement("script") synchronously
    text
    copied!<p>Is it possible to call in a <code>.js</code> file synchronously and then use it immediately afterward?</p> <pre><code>&lt;script type="text/javascript"&gt; 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(); }; &lt;/script&gt; </code></pre> <p>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.</p> <p>Thoughts?</p> <p>Edit:</p> <p>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.</p> <pre><code>// Include() is a custom function to import js. Include('my1.js'); Include('my2.js'); myFunc1('blarg'); myFunc2('bleet'); </code></pre> <p>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."</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload