繁体   English   中英

如何延迟我的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 但是现在不再允许以同步方式调用AJAX函数( 至少使用jQuery )。 那么...如何确保在回调完成之前不调用我的whatever方法?

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

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

$.holdReady()方法允许调用者延迟jQuery的ready事件。 高级功能通常用于在允许就绪事件发生之前进行加载。

因此,在我的情况下,代码应如下所示:

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

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

使用自定义事件的另一种选择 (由于在评论中使用freedom -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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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