How to detect whether your Javascript is being included synchronously or asynchronously
<p>I am trying to detect whether the current Javascript file that's being executed is included synchronously (via a regular script tag)</p>

<pre><code>&lt;script src="myscript.js"&gt;&lt;/script&gt;
</code></pre>

<p>or asynchronously via inserting a script element into the DOM programatically, something like</p>

<pre><code>var script = document.createElement('script')
script.src = 'myscript.js'
document.body.appendChild(script)
</code></pre>

<p>and consequently whether <code>document.write</code> can be used or not. I've figured out a crazy solution which tests whether <code>document.write</code> works, see <a href="https://gist.github.com/1889980" rel="nofollow">this gist</a>.</p>

<p>Basically, it works by using <code>document.write</code> to write out an element - I chose an empty script tag. Then it queries the DOM to determine whether that script element was successfully written out. If it was - the script must have be included synchronously, if it wasn't - it was included asynchronously. </p>

<p>This solution works in all browsers I've tested so far (all major ones including IE7+) except for Opera. </p>

<p>The question is: is there a better solution? </p>

<p><em>Note: I have also tried checking <code>document.readyState</code>, but that does not appear to be helpful in IE.</em></p>

<p><em>Also note: I don't need a lecture that <code>document.write</code> is evil. I know.</em></p>

<p><em>Update: turns out that in addition to not working on Opera, my technique is also unreliable in certain cases in IE and other browsers - <code>document.write</code> may or may not work depending on timing or caching scenario. The <a href="http://dev.w3.org/html5/spec-LC/apis-in-html-documents.html#document.write" rel="nofollow">spec</a> seems to say as much.</em></p>
