Pergunta

Eu estou trabalhando em um site que contém um monte de mp3s e imagens, e eu gostaria de exibir uma carga gif, enquanto todas as cargas de conteúdo.

Eu não tenho nenhuma idéia de como conseguir isso, mas eu tenho o GIF animado que eu quero usar.

Todas as sugestões?

Foi útil?

Solução

Normalmente sites que fazem isso por carregar conteúdo via ajax e ouvindo o evento readystatechanged para atualizar o DOM com um GIF carga ou o conteúdo.

Como você está atualmente carregar o seu conteúdo?

O código seria semelhante a esta:

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);
}

Há uma abundância de 3 bibliotecas partido JavaScript que podem tornar sua vida mais fácil, mas o acima é realmente tudo o que você precisa.

Outras dicas

Você disse que não queria fazer isso em AJAX. Enquanto AJAX é ótimo para isso, há uma maneira de mostrar um DIV enquanto espera para toda a <body> a carga. É algo como isto:

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

O evento onload não dispara até que toda a página foi carregada. Assim, o <DIV> layer2 não será exibido até que a página de carregamento terminado, após o qual onload dispara.

Que tal com jQuery? Um simples ...

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

E o HTML ...

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

E CSS ...

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

Então em seu div loader você iria colocar o GIF, e qualquer texto que você queria, e ele vai desaparecer uma vez que a página foi carregada.

Em primeiro lugar, criar uma imagem de carregamento em um div. Em seguida, obter o elemento div. Em seguida, defina uma função que edita o CSS para tornar a visibilidade para "escondido". Agora, no <body>, coloque o onload ao nome da função.

#Pure método css

Coloque isso no topo do seu código (antes tag header)

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

E isso no fundo depois de todos os outros códigos (exceto / html tag)

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

Isso sempre funciona para mim 100% do tempo

Há realmente uma maneira muito fácil de fazer isso. O código deve 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);

    }

E no HTML:

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

Eu fiz algo parecido na minha página e ele funciona muito bem.

Você pode usar o elemento <progress> em HTML5. Veja esta página para código fonte e demonstração ao vivo. http://purpledesign.in/blog/super-cool-loading-bar- html5 /

aqui é o elemento de progresso ...

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

este terá o valor de carga a partir de 20. É claro que apenas o elemento não vai bastar. Você precisa mover-lo como as cargas de script. Para isso, precisamos JQuery. Aqui está um script simples JQuery que começa o progresso de 0 a 100 e faz algo no slot de tempo 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>

Adicione esta ao seu arquivo 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 isso lhe dará um começo.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top