如何继续检查JavaScript功能是否可用,然后调用一次

时间:2021-11-07 09:05:02

My project consists of several files. I have a JavaScript function, window.toggleLayer() that is defined in a dojo require block in second.js, and my main jQuery is located in first.js. I have to keep the code separate because of using dojo and jQuery, as well as for other reasons. As a result, I'm not able to move my code around to prevent the issue I'm having.

我的项目包含几个文件。我有一个JavaScript函数,window.toggleLayer()在second.js中的dojo require块中定义,而我的主jQuery位于first.js中。由于使用了dojo和jQuery,以及其他原因,我必须将代码分开。结果,我无法移动我的代码来防止我遇到的问题。

When the page loads, first.js loads (call the function here), and then second.js (where the function exists) loads.

当页面加载时,first.js加载(在这里调用函数),然后加载second.js(函数存在的地方)。

At the time I need to call window.toggleLayer() in first.js, it is not available, and I end up getting the following error:

当我需要在first.js中调用window.toggleLayer()时,它不可用,我最终得到以下错误:

TypeError: window.toggleLayer is not a function
window.toggleLayer(pKey, true);

What I ended up doing after finally figuring out the issue was a timing issue, I put setTimout around the function:

在最终找出问题后我最终做的是时间问题,我把setTimout放在函数周围:

setTimeout(function () {
    if(typeof window.toggleLayer == 'function'){
        window.toggleLayer(pKey, true);
    }
}, 1000);

The function now loads after 1 second. But as my project becomes heavier, 1 second will more than likely change. I can change this value to 2500 or higher, but this seems quite inefficient.

该功能现在在1秒后加载。但随着我的项目变得越来越重,1秒钟很可能会改变。我可以将此值更改为2500或更高,但这似乎效率很低。

Is there a way to keep checking, dynamically, if the function exists? And if it exists, stop checking if it exists and then call it?

如果函数存在,有没有办法动态地检查?如果它存在,停止检查它是否存在然后调用它?

1 个解决方案

#1


2  

Try this:

function tryToggleLayer(){
  if(window.toggleLayer){ // check if function exists
     
    // If function exists, call it
    window.toggleLayer(pKey, true);
  }else{
    
    // If not, try again in one second
    setTimeout(tryToggleLayer, 1000);
  }
}

tryToggleLayer();

That way you can check if the function is ready every one second, using recursion

这样,您可以使用递归检查函数是否每秒都准备就绪

#1


2  

Try this:

function tryToggleLayer(){
  if(window.toggleLayer){ // check if function exists
     
    // If function exists, call it
    window.toggleLayer(pKey, true);
  }else{
    
    // If not, try again in one second
    setTimeout(tryToggleLayer, 1000);
  }
}

tryToggleLayer();

That way you can check if the function is ready every one second, using recursion

这样,您可以使用递归检查函数是否每秒都准备就绪