Example 1: DOM Insertion Function
head tag is found and cached, and each time the function executes a new script tag is created and appended to the
head. The callback method is attached to the
onload event, instead it fires the
onreadystatechange event also fires each time the
readyState property of the event changes, so once for
loading and once of
loaded, so we wrap the callback and check for the right state. I also check for
completed, because a lot of similar examples on the web were using it, however, my personal experience is that the state is set to
true when a script is imported and
false when it already exists.
Note: In some browsers, such as Opera, both the
onload event are fired. To handle this, I have added Boolean,
doCallback, that checks to see if the callback has executed yet.
In Example 2 the
testObject is only accessed from inside of the callback, but it has been added to window, so any code on your page has access to it once the callback function executes. If there are many dependencies on
testObject, creating a CustomEvent for the dependencies to subscribe to, and firing that CustomEvent as the callback, can simplify your code.