简体   繁体   中英

Javascript checking if function exists using a closure and arguments.callee

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.callee like this:

(function() {
  function check() {
    if(typeof myFunction === "undefined") {
      console.log("not loaded");
      setTimeout(check, 100);
    } else {
      console.log("loaded");
    }
  }
  check();
})();

A good reason to stop using arguments.callee is 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.

arguments.callee() is not allowed in strict mode and seems to be deprecated. According to the Mozilla Developer Network it also prevents a large number of possible optimizations.

An alternative approach would be to give your function expression a name and use that one in setTimeout. The name would only only be visible from within the function.

(function pollingFunction() {
  if(typeof myFunction === "undefined") {
    console.log("not loaded");
    setTimeout(pollingFunction, 100);
  } else {
    console.log("loaded");
  }
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM