Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect whether your Javascript is being included synchronously or asynchronously

Tags:

javascript

I am trying to detect whether the current Javascript file that's being executed is included synchronously (via a regular script tag)

<script src="myscript.js"></script>

or asynchronously via inserting a script element into the DOM programatically, something like

var script = document.createElement('script')
script.src = 'myscript.js'
document.body.appendChild(script)

and consequently whether document.write can be used or not. I've figured out a crazy solution which tests whether document.write works, see this gist.

Basically, it works by using document.write 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.

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

The question is: is there a better solution?

Note: I have also tried checking document.readyState, but that does not appear to be helpful in IE.

Also note: I don't need a lecture that document.write is evil. I know.

Update: turns out that in addition to not working on Opera, my technique is also unreliable in certain cases in IE and other browsers - document.write may or may not work depending on timing or caching scenario. The spec seems to say as much.

like image 589
airportyh Avatar asked Nov 04 '22 05:11

airportyh


1 Answers

this is evil but you could redefine the document functions and write your own. something like this perhaps:

var oldAppendChild = document.body.appendChild;

document.body.appendChild = function(child) {
    //examine if child is a script element, do stuff with it if it is
    //finally do what the original function did and:
    oldAppendChild(child);
}

of course you would need to handle all the different browser quirks and and all the different ways one could add a script element to the page, but it is an alternative to what you describe

like image 166
Darko Z Avatar answered Nov 07 '22 20:11

Darko Z