I using a nice trick to check if an async loaded javascript file with a function myFunction exists. The trick is a closure using arguments.callee:
(function() {
if(typeof myFunction === "undefined") {
console.log("not loaded");
setTimeout(arguments.callee, 100);
} else {
console.log("loaded");
}
})();
Is this the best way of doing this though? Is there any issue with browser compatibility using arguments.callee?
Thanks.
First off, you should not poll for the presence of a function. If possible, you should monitor for an event that is triggered when the script is loaded. See this article for how to monitor for the loading of dynamically loaded scripts and you can easily find other examples via Google.
If the script is loaded via a
<script>tag and it’s not async or defer then it will be loaded sychronously so that any code after will be safe to access that script.While it would be better to use the actual event that is triggered when the script is loaded (and that’s really what you should figure out how to do), you can wean your technique from
arguments.calleelike this:A good reason to stop using
arguments.calleeis that it is not present in ECMA5 strict mode.If you care to provide some context for how the script with this function in it is being loaded, then we might be able to provide you some options for better ways to know when it’s loaded because polling for it is certainly not the best way.