I am trying to determine if the current Javascript executable is enabled synchronously (via a regular script tag)
<script src="myscript.js"></script>
or asynchronously by inserting a script element into the DOM programmatically, something like
var script = document.createElement('script')
script.src = 'myscript.js'
document.body.appendChild(script)
and therefore whether it can be used document.writeor not. I figured out a crazy solution that checks if it works document.write, see this point .
Basically, it works using an document.writeelement to write - I selected an empty script tag. He then queries the DOM to determine if this script element has been successfully written. If it was - the script should be included synchronously, if it was not - it was included asynchronously.
This solution works in all browsers that I have tested so far (all major ones, including IE7 +), with the exception of Opera.
Question: is there a better solution?
Note. I also tried checking document.readyState, but this does not seem to be useful in IE.
Also note: I do not need a lecture, which document.writeis evil. I know.
Update: it turns out that in addition to what does not work in Opera, my technique is also unreliable in some cases in IE and other browsers - it document.writemay or may not work depending on the synchronization or caching scenario. spec seems to say the same.
source
share