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