简体   繁体   English

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

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

I have a web application built with jQuery, and I need to load some JSON data before anything else is done. 我有一个使用jQuery构建的Web应用程序, 完成任何其他操作之前 ,我需要加载一些JSON数据。 Currently, I'm doing it like this: 目前,我正在这样做:

<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>

It works, but it's extremely ugly. 它可以工作,但是非常丑陋。 I'd rather load the actual JSON file, for example using jQuery's getJSON with a callback function. 我宁愿加载实际的JSON文件,例如使用带有回调函数的jQuery的getJSON But calling AJAX functions in a synchronous way isn't allowed anymore ( at least with jQuery ). 但是现在不再允许以同步方式调用AJAX函数( 至少使用jQuery )。 So... how do I make sure that my whatever method isn't called until that callback has finished? 那么...如何确保在回调完成之前不调用我的whatever方法?

Just calling $(whatever) from my callback function is not an option, because I actually have many of those $() distributed across the different pages of the application. 仅从我的回调函数调用$(whatever)是不可行的,因为实际上我有许多$()分布在应用程序的不同页面上。

I have found two different ways to implement it. 我发现了两种不同的实现方法。 First, using the .holdReady() function in jQuery: 首先,在jQuery中使用.holdReady()函数

The $.holdReady() method allows the caller to delay jQuery's ready event. $.holdReady()方法允许调用者延迟jQuery的ready事件。 This advanced feature would typically be used [...] to load [...] before allowing the ready event to occur 高级功能通常用于在允许就绪事件发生之前进行加载。

So in my case, the code should look like this: 因此,在我的情况下,代码应如下所示:

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

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

Another option, using custom events (thanks to freedomn-m 's suggestion in the comments), would be something like this: 使用自定义事件的另一种选择 (由于在评论中使用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>

The only change required is to replace all the $(whatever); 唯一需要的更改是替换所有的$(whatever); for $(document).on('jsonReady', whatever); $(document).on('jsonReady', whatever); .

There is a simpler way of doing things ;) 有一种更简单的方法;)

 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