Display spinner while DataTables table loads Ruby on Rails

后端 未结 4 1606
无人共我
无人共我 2021-01-12 06:05

Using Rails I have built a web app. One of the pages of the web app displays a table which uses the DataTables API. This JSFiddle shows an example of what my web app looks l

4条回答
  •  臣服心动
    2021-01-12 06:49

    If the data is loaded in Ruby, there's no point in loading a spinner because the data has already loaded by then. This is a bare-bones ordering of what happens in your Rails app:

    1. Controller then view Ruby executes, rendering HTML
    2. HTML is sent to client
    3. Client requests linked CSS and JS in order
    4. CSS and JS execute in order
    5. Asynchronous JS finishes

    So, the majority of your delay is happening at step 1, but a CSS/JS spinner won't load until step 4. If you want to use a spinner, you need to load the data via async Ajax, so you can load the spinner in 4, then finish loading data and remove spinner in 5. Using jQuery Ajax:

    var spinner = new Spinner().spin(document.getElementById('spinner'));
    $.ajax("/your/data/path.json")
    .done(function(data) {
      // load data here, then load table:
      var table = $('#app-list-table').DataTable({ … })
      // remove spinner
      $('#spinner').remove();
    });
    

    You could of course add the spinner to your current code:

    var spinner = new Spinner().spin(document.getElementById('spinner'));
    $('#app-list-table').DataTable({ 
      …
      initComplete: function() { $('#spinner').remove(); }
    })
    

    However, again, since most of the delay happens in Ruby, you'll only see the spinner for a brief moment at the end of the delay. To see the spinner for the whole delay, use Ajax.

提交回复
热议问题