Como mostrar uma barra de progresso em execução enquanto a página está a carregar
quero mostrar uma barra de progresso em execução enquanto a minha página está a carregar como aqui, na minha página. Eu usei uma imagem de carregamento simples no meu exemplo, mas eu quero convertê-lo em uma barra de progresso em execução. Aqui está o meu código:
$(window).load(function() {
alert("hi");
$('#loading').hide();
});
#loading {
width: 100%;
height: 100%;
top: 0px;
left: 0px;
position: fixed;
display: block;
opacity: 0.7;
background-color: #fff;
z-index: 99;
text-align: center;
}
#loading-image {
position: absolute;
top: 100px;
left: 240px;
z-index: 100;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div id="loading">
<img id="loading-image" src="http://cdn.nirmaltv.com/images/generatorphp-thumb.gif" alt="Loading..." />
</div>
<div id="txt">
<h2>Let AJAX change this text</h2>
</div>
<button>Change Content</button>
7 answers
Existem alguns plugins que já fizeram isso, como nprogress.js,pace.js e este Youtube-like one. Se quiseres ser tu a fazê-lo, podes ver o código deles lá dentro.
Copiei o código relevante abaixo de esta página. Espero que isto te ajude.
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
console.log(percentComplete);
}
}, false);
//Download progress
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
console.log(percentComplete);
}
}, false);
return xhr;
},
type: 'POST',
url: "/",
data: {},
success: function(data) {
//Do something success-ish
}
});
Nesta amostra, eu criei uma barra de progresso JavaScript (com visualização percentual), você pode controlá-la e escondê-la com JavaScript.
Nesta amostra, a barra de progresso avança a cada 100m. pode vê-la em JSFiddle
var elapsedTime = 0;
var interval = setInterval(function() {
timer()
}, 100);
function progressbar(percent) {
document.getElementById("prgsbarcolor").style.width = percent + '%';
document.getElementById("prgsbartext").innerHTML = percent + '%';
}
function timer() {
if (elapsedTime > 100) {
document.getElementById("prgsbartext").style.color = "#FFF";
document.getElementById("prgsbartext").innerHTML = "Completed.";
if (elapsedTime >= 107) {
clearInterval(interval);
history.go(-1);
}
} else {
progressbar(elapsedTime);
}
elapsedTime++;
}
Ficheiro Html
<div class='progress' id="progress_div">
<div class='bar' id='bar1'></div>
<div class='percent' id='percent1'></div>
</div>
<div id="wrapper">
<div id="content">
<h1>Display Progress Bar While Page Loads Using jQuery<p>TalkersCode.com</p></h1>
</div>
</div>
Ficheiro Js
document.onreadystatechange = function(e) {
if (document.readyState == "interactive") {
var all = document.getElementsByTagName("*");
for (var i = 0, max = all.length; i < max; i++) {
set_ele(all[i]);
}
}
}
function check_element(ele) {
var all = document.getElementsByTagName("*");
var totalele = all.length;
var per_inc = 100 / all.length;
if ($(ele).on()) {
var prog_width = per_inc + Number(document.getElementById("progress_width").value);
document.getElementById("progress_width").value = prog_width;
$("#bar1").animate({
width: prog_width + "%"
}, 10, function() {
if (document.getElementById("bar1").style.width == "100%") {
$(".progress").fadeOut("slow");
}
});
} else {
set_ele(ele);
}
}
function set_ele(set_element) {
check_element(set_element);
}
Definitivamente resolve o seu problema para um tutorial completo aqui está o link http://talkerscode.com/webtricks/display-progress-bar-while-page-loads-using-jquery.php
Passos simples, siga-os e acho que vai resolver o seu problema
Inclui estes Css na tua Página,
.progress {
position: relative;
height: 2px;
display: block;
width: 100%;
background-color: white;
border-radius: 2px;
background-clip: padding-box;
/*margin: 0.5rem 0 1rem 0;*/
overflow: hidden;
}
.progress .indeterminate {
background-color:black; }
.progress .indeterminate:before {
content: '';
position: absolute;
background-color: #2C67B1;
top: 0;
left: 0;
bottom: 0;
will-change: left, right;
-webkit-animation: indeterminate 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
animation: indeterminate 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite; }
.progress .indeterminate:after {
content: '';
position: absolute;
background-color: #2C67B1;
top: 0;
left: 0;
bottom: 0;
will-change: left, right;
-webkit-animation: indeterminate-short 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite;
animation: indeterminate-short 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite;
-webkit-animation-delay: 1.15s;
animation-delay: 1.15s; }
@-webkit-keyframes indeterminate {
0% {
left: -35%;
right: 100%; }
60% {
left: 100%;
right: -90%; }
100% {
left: 100%;
right: -90%; } }
@keyframes indeterminate {
0% {
left: -35%;
right: 100%; }
60% {
left: 100%;
right: -90%; }
100% {
left: 100%;
right: -90%; } }
@-webkit-keyframes indeterminate-short {
0% {
left: -200%;
right: 100%; }
60% {
left: 107%;
right: -8%; }
100% {
left: 107%;
right: -8%; } }
@keyframes indeterminate-short {
0% {
left: -200%;
right: 100%; }
60% {
left: 107%;
right: -8%; }
100% {
left: 107%;
right: -8%; } }
Depois inclui a barra de progresso a tua marca corporal,
<div class="progress" id="PreLoaderBar">
<div class="indeterminate"></div>
</div>
Então ele vai começar como a sua página carrega, e agora o que você tem que fazer é apenas esconder isso quando a página carrega, ou definir a visibilidade para nenhum, ou escondido, usando javascript,
document.onreadystatechange = function () {
if (document.readyState === "complete") {
console.log(document.readyState);
document.getElementById("PreLoaderBar").style.display = "none";
}
}
Deixe-me saber se você enfrenta algum problema e também, você pode adicionar qualquer tipo de barra de progresso que você pode facilmente encontrá-los, para este exemplo eu usei uma barra de progresso indeterminada.
Acho que é disto que estás à procura barra de progresso suave . Isto mostra uma barra de progresso, bem como a percentagem durante o carregamento!