如何延迟我的 javascript 代码直到加载 JSON 文件?

How to delay my javascript code until a JSON file is loaded?

我有一个使用 jQuery 构建的 Web 应用程序,我需要加载一些 JSON 数据,然后 其他任何事情完成之前。目前,我是这样做的:

<html>
  ...
  <script type="text/javascript">
    // Load the data (directly injected into the HTML)
    var json = { ... };

    // Once the full DOM is loaded, do whatever I need
    $(whatever);

    function whatever() { ... }
  </script>
  ...
</html>

它有效,但它非常丑陋。我宁愿加载实际的 JSON 文件,例如使用 jQuery 的 getJSON with a callback function. But calling AJAX functions in a synchronous way isn't allowed anymore (at least with jQuery)。那么...如何确保在回调完成之前不调用我的 whatever 方法?

仅从我的回调函数中调用 $(whatever) 不是一种选择,因为实际上我有许多 $() 分布在应用程序的不同页面上。

我找到了两种不同的实现方法。首先,在jQuery中使用.holdReady()函数

The $.holdReady() method allows the caller to delay jQuery's ready event. This advanced feature would typically be used [...] to load [...] before allowing the ready event to occur

所以在我的例子中,代码应该是这样的:

<html>
  ...
  <script type="text/javascript">
    var json = {};
    $.holdReady(true);
    $.getJSON(url, '', function(data) {
      json = data;
      $.holdReady(false);
    });

    $(whatever);
  </script>
  ...
</html>

另一个选项,使用custom events(感谢freedomn-m在评论中的建议),将是像这样:

<html>
  ...
  <script type="text/javascript">
    var json = {};
    // Request the JSON file
    $.getJSON(url, '', function(data) {
      // When it's retrieved, store the data in the `json` variable
      json = data;
      // And when the DOM is ready...
      $(function() {
        // ...trigger the custom `jsonReady` event
        $(document).trigger('jsonReady');
      });
    });
  </script>
  ...
</html>

唯一需要更改的是将 $(whatever); 替换为 $(document).on('jsonReady', whatever);

有一种更简单的处理方法 ;)

let json = {}
$(document).ready(() => {
  function whatever() {
    // do some stuff
    console.log('run the program');
  }
  $.getJSON('https://jsonplaceholder.typicode.com/users', (data) => {
      json = data;
      console.log(json);
    })
    .then(() => whatever());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Some paragraph</p>