Show progress bar with values while loading subpage

13

I have a preload or progress that I show before being redirected to another page.

What I want is that while it is loading to open another page, the div of the progress is increasing up to 100%, as well as a numerical value (n / 100).

I currently have the following code:

var ajax_load = "<div class='progress'>" + "<div id='progress_id'   class='progress-bar progress-bar-striped active' " +
                    "role='progressbar' aria-valuenow='20' aria-valuemin='0' aria-valuemax='100' style='width: 45%'>" +
                    "n/100</div></div>";

$("#menu_navegacion_inicio").click(function (ev) {
        ev.preventDefault();
        var href = $(this).attr('href');        
        $("#subpagina").html(ajax_load).load(baseUrl + href, function () {
        });
    });

In ajax_load I call the progress, but I need the value of the attribute aria-valuenow , go increasing to 100, and n also increase to 100, where n / 100.

I would like to pass values to it while the page starts loading, indicating the delay time, which starts from 0% to 100%, once the progress load is finished, the page I requested opens.

I was thinking of using some iteration and pass something like this:

........
.....
var valeur= valeur +10;
........
$('#progress_id').css('width', valeur+'%').attr('aria-valuenow', valeur);  
$('#progress_id').append(valeur + '/100')
......
......

But I do not know how I do it, if anyone knows I would appreciate it a lot. I do not know if I understand what I said

    
asked by Danilo 12.02.2016 в 01:53
source

2 answers

7

You can do something like what is explained in this StackOverflow question or on the Dave's website Bond (both links in English). The idea is that the second version of XMLHttpRequest includes the onprogress event that you can listen to and that will return interesting information such as:

  • What is the total size of the download.
  • How much has been downloaded so far.
  • The timestamp of the moment in which the event occurs.

With the first two you can calculate the percentage completed (size downloaded / total size) and with the second you can calculate how long the download is taking (timestamp of onprogress - timestamp from when the initial request was made).

You should change the load() to ajax() but that should not be a problem. Applied to your code the change would look like this:

var baseUrl = "";
var ajax_load = "<div class='progress'>" + "<div id='progress_id' class='progress-bar progress-bar-striped active' " +
                "role='progressbar' aria-valuenow='0' aria-valuemin='0' aria-valuemax='100' style='width: 45%'>" +
                "n/100</div></div>";

$("#menu_navegacion_inicio").on("click", function(ev) {
  // estas dos lineas no cambian
  ev.preventDefault();
  var href = $(this).attr('href');

  // sustituir el contenido de subpagina con el mensaje de carga       
  $("#subpagina").html(ajax_load);

  // hacer llamada ajax al href
  $.ajax({
    url: baseUrl + href,
    // cuando se completa la petición
    success: function(codigo){
      // rellenar la subpagina con el HTML obtenido
      $("#subpagina").html(codigo);
    },
    // modificar el valor de xhr a nuestro gusto
    xhr: function(){
      // obtener el objeto XmlHttpRequest nativo
      var xhr = $.ajaxSettings.xhr() ;
      // añadirle un controlador para el evento onprogress
      xhr.onprogress = function(evt){ 
        // calculamos el porcentaje y nos quedamos sólo con la parte entera
        var porcentaje = Math.floor((evt.loaded/evt.total*100));
        // actualizamos el texto con el porcentaje mostrado
        $("#progress_id").text(porcentaje + "/100");
        // actualizamos la cantidad avanzada en la barra de progreso
        $("#progress_id").attr("aria-valuenow", porcentaje); 
        $("#progress_id").css("width", porcentaje + "%"); 
      };
      // devolvemos el objeto xhr modificado
      return xhr ;
    }
  });
});

And here is an example of how it would work with downloading a large image (2.75MB). If you have already seen the image, you may need to clear the cache to see the progress bar:

<!doctype html>
<html>
  <head>
    <title>Test Onprogress</title>
  </head>
  <body>

    <a id="menu_navegacion_inicio" href="https://i.imgur.com/Bq6ryBM.jpg">Click here</a>
    <div id="subpagina"></div>

    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-7s5uDGW3AHqw6xtJmNNtr+OBRJUlgkNJEo78P4b0yRw= sha512-nNo+yCHEyn0smMxSswnf/OnX6/KwJuZTlNZBjauKhTK0c+zT+q5JOCx0UFhXQ6rJR9jg6Es8gPuD2uZcYDLqSw==" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha256-KXn5puMvxCw+dAYznun+drMdG1IFl3agK0p/pqT9KAo= sha512-2e8qq0ETcfWRI4HJBzQiA3UoyFk6tbNyG+qSaIBZLyW9Xf3sWZHN/lxe9fTh1U45DpPf07yj94KsUHHWe4Yk1A==" crossorigin="anonymous"></script>
    <script>
      baseUrl = "";
      var ajax_load = "<div class='progress'>" + "<div id='progress_id' class='progress-bar progress-bar-striped active' " +
          "role='progressbar' aria-valuenow='0' aria-valuemin='0' aria-valuemax='100' style='width: 0%'>" +
          "n/100</div></div>";

      $("#menu_navegacion_inicio").on("click", function(ev) {
        // estas dos lineas no cambian
        ev.preventDefault();
        var href = $(this).attr('href');

        // sustituir el contenido de subpagina con el mensaje de carga       
        $("#subpagina").html(ajax_load);

        // hacer llamada ajax al href
        $.ajax({
          url: baseUrl + href,
          // cuando se completa la petición
          success: function(codigo){
            // rellenar la subpagina con el HTML obtenido
            $("#subpagina").html("COMPLETADO!");
          },
          // modificar el valor de xhr a nuestro gusto
          xhr: function(){
            // obtener el objeto XmlHttpRequest nativo
            var xhr = $.ajaxSettings.xhr() ;
            // añadirle un controlador para el evento onprogress
            xhr.onprogress = function(evt){ 
              // calculamos el porcentaje y nos quedamos sólo con la parte entera
              var porcentaje = Math.floor((evt.loaded/evt.total*100));
              // actualizamos el texto con el porcentaje mostrado
              $("#progress_id").text(porcentaje + "/100");
              // actualizamos la cantidad avanzada en la barra de progreso
              $("#progress_id").attr("aria-valuenow", porcentaje); 
              $("#progress_id").css("width", porcentaje + "%"); 
            };
            // devolvemos el objeto xhr modificado
            return xhr ;
          }
        });
      });
    </script>
  </body>
</html>
    
answered by 12.02.2016 в 04:42
4

Greetings, There is a very good plugin called PACE , that has helped me personally not to have to wear myself out in this kind of things and allows me to concentrate on what is really important.

This plugin takes care of everything, it is very light and easy to use. In addition, it supports bower and it is opensource, you can check it here: link the repo on GitHub is: link

    
answered by 14.02.2016 в 03:12