Pregunta

Estoy trabajando en un sitio que contiene un montón de mp3 e imágenes, y me gustaría mostrar un gif de carga mientras se carga todo el contenido.

No tengo idea de cómo lograr esto, pero tengo el gif animado que quiero usar.

¿Alguna sugerencia?

¿Fue útil?

Solución

Por lo general, los sitios que hacen esto cargando contenido a través de ajax y escuchando el evento readystatechanged para actualizar el DOM con un GIF de carga o el contenido.

¿Cómo está cargando actualmente su contenido?

El código sería similar a esto:

function load(url) {
    // display loading image here...
    document.getElementById('loadingImg').visible = true;
    // request your data...
    var req = new XMLHttpRequest();
    req.open("POST", url, true);

    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            // content is loaded...hide the gif and display the content...
            if (req.responseText) {
                document.getElementById('content').innerHTML = req.responseText;
                document.getElementById('loadingImg').visible = false;
            }
        }
    };
    request.send(vars);
}

Hay muchas bibliotecas javascript de terceros que pueden facilitarle la vida, pero lo anterior es realmente todo lo que necesita.

Otros consejos

Dijiste que no querías hacer esto en AJAX. Si bien AJAX es excelente para esto, hay una manera de mostrar un DIV mientras se espera que se cargue todo el <body>. Va más o menos así:

<html>
  <head>
    <style media="screen" type="text/css">
      .layer1_class { position: absolute; z-index: 1; top: 100px; left: 0px; visibility: visible; }
      .layer2_class { position: absolute; z-index: 2; top: 10px; left: 10px; visibility: hidden }
    </style>
    <script>
      function downLoad(){
        if (document.all){
            document.all["layer1"].style.visibility="hidden";
            document.all["layer2"].style.visibility="visible";
        } else if (document.getElementById){
            node = document.getElementById("layer1").style.visibility='hidden';
            node = document.getElementById("layer2").style.visibility='visible';
        }
      }
    </script>
  </head>
  <body onload="downLoad()">
    <div id="layer1" class="layer1_class">
      <table width="100%">
        <tr>
          <td align="center"><strong><em>Please wait while this page is loading...</em></strong></p></td>
        </tr>
      </table>
    </div>
    <div id="layer2" class="layer2_class">
        <script type="text/javascript">
                alert('Just holding things up here.  While you are reading this, the body of the page is not loading and the onload event is being delayed');
        </script>
        Final content.      
    </div>
  </body>
</html>

El evento de carga no se activará hasta que se haya cargado toda la página. Por lo tanto, la capa2 <DIV> no se mostrará hasta que la página haya terminado de cargarse, después de lo cual se activará la carga.

¿Qué tal con jQuery? Un simple ...

$(window).load(function() {      //Do the code in the {}s when the window has loaded 
  $("#loader").fadeOut("fast");  //Fade out the #loader div
});

Y el HTML ...

<div id="loader"></div>

Y CSS ...

#loader {
      width: 100%;
      height: 100%;
      background-color: white;
      margin: 0;
}

Luego, en su cargador div colocaría el GIF y cualquier texto que quisiera, y se desvanecerá una vez que la página se haya cargado.

Primero, configure una imagen de carga en un div. A continuación, obtenga el elemento div. Luego, configure una función que edite el css para hacer que la visibilidad sea & Quot; hidden & Quot ;. Ahora, en el <body>, ponga la carga al nombre de la función.

#Pure css method

  

Coloque esto en la parte superior de su código (antes de la etiqueta del encabezado)

<style> .loader {
  position: fixed;
  background-color: #FFF;
  opacity: 1;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 10;
}
</style>
<div class="loader">
  Your Content For Load Screen
</div>

  

Y esto en la parte inferior después de todos los demás códigos (excepto la etiqueta / html)

<style>
.loader {
    -webkit-animation: load-out 1s;
    animation: load-out 1s;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}

@-webkit-keyframes load-out {
    from {
        top: 0;
        opacity: 1;
    }

    to {
        top: 100%;
        opacity: 0;
    }
}

@keyframes load-out {
    from {
        top: 0;
        opacity: 1;
    }

    to {
        top: 100%;
        opacity: 0;
    }
}
</style>

  
    

Esto siempre funciona para mí el 100% del tiempo

  

En realidad, hay una manera bastante fácil de hacer esto. El código debería ser algo como:

<script type="test/javascript">

    function showcontent(x){

      if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
      } else {
        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
      }

      xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 1) {
            document.getElementById('content').innerHTML = "<img src='loading.gif' />";
        }
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          document.getElementById('content').innerHTML = xmlhttp.responseText;
        } 
      }

      xmlhttp.open('POST', x+'.html', true);
      xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
      xmlhttp.send(null);

    }

Y en el HTML:

<body onload="showcontent(main)"> <!-- onload optional -->
<div id="content"><img src="loading.gif"></div> <!-- leave img out if not onload -->
</body>

Hice algo así en mi página y funciona muy bien.

Puede usar el elemento <progress> en HTML5. Vea esta página para el código fuente y la demostración en vivo. http://purpledesign.in/blog/super-cool-loading-bar- html5 /

aquí está el elemento de progreso ...

<progress id="progressbar" value="20" max="100"></progress>

esto tendrá el valor de carga a partir de 20. Por supuesto, solo el elemento no será suficiente. Necesita moverlo a medida que se carga el script. Para eso necesitamos JQuery. Aquí hay un script simple de JQuery que comienza el progreso de 0 a 100 y hace algo en un intervalo de tiempo definido.

<script>
        $(document).ready(function() {
         if(!Modernizr.meter){
         alert('Sorry your brower does not support HTML5 progress bar');
         } else {
         var progressbar = $('#progressbar'),
         max = progressbar.attr('max'),
         time = (1000/max)*10, 
         value = progressbar.val();
        var loading = function() {
        value += 1;
        addValue = progressbar.val(value);
        $('.progress-value').html(value + '%');
        if (value == max) {
        clearInterval(animate);
        //Do Something
 }
if (value == 16) {
//Do something 
}
if (value == 38) {
//Do something
}
if (value == 55) {
//Do something 
}
if (value == 72) {
//Do something 
}
if (value == 1) {
//Do something 
}
if (value == 86) {
//Do something 
    }

};
var animate = setInterval(function() {
loading();
}, time);
};
});
</script>

Agregue esto a su archivo HTML.

<div class="demo-wrapper html5-progress-bar">
<div class="progress-bar-wrapper">
 <progress id="progressbar" value="0" max="100"></progress>
 <span class="progress-value">0%</span>
</div>
 </div>

Espero que esto te dé un comienzo.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top