How can I delay the execution of a script block until after an external script has loaded?
<p>I'm trying to dynamically insert and execute a couple of scripts, and I think I'm hitting a race condition where the second is trying to execute before the first is loaded. </p>

<p>The project I'm working on has an unusual requirement: <strong>I am unable to modify the page's HTML source.</strong> It's compiled into an app for localization purposes. </p>

<p>Therefore, I'm unable to insert <code>&lt;script&gt;</code> tags like I normally would to link in JavaScript files. </p>

<p>It turns out that the client wants to use a hosted web font, so I decided to build and append the two required <code>&lt;script&gt;</code> tags dynamically in an already-linked JavaScript file.</p>

<p>The <code>&lt;script&gt;</code> blocks are appending correctly in the <code>head</code> of the document, but function in the second block seems to be firing before the external script linked in the first <code>&lt;script&gt;</code> tag is fully loaded, and it's throwing an <code>undefined</code> error.</p>

<p>Here's the relevant piece of code: </p>

<pre><code>document.getElementsByTagName("head")[0];
var tag = document.createElement('script');
tag.setAttribute("src", "http://use.typekit.com/izj3fep.js");
document.getElementsByTagName("head")[0].appendChild(tag);

try {
        Typekit.load(); // This is executing too quickly!

    } catch(e){
        console.log("Hosted fonts failed to load: " + e);
}
</code></pre>

<p>I tried moving the <code>try</code> block to the <code>window.onload</code> event, but that fires before any of this code is called.</p>

<p>I guess I could dynamically load jQuery and then use it's <code>ready</code> event, but that seems pretty heavy-handed. I'm hesitant to pull in a library on this project, as the client has a lot of custom JavaScript that could potentially clash with it.</p>

<p>What else can I try?</p>
