Display a label while the page is loading

Asked

Viewed 168 times

2

I’m trying to create a label, that appears while the page is loading, with a "a carregar".

And once the page is fully loaded, hide the label.

My code is this::

document.getElementById("lblmsg").innerHTML = "carregar...";

for(var i=1; i>1000; i++){
  var value = i*i*i*i;
}

function callFunction(){
  document.getElementById("lblmsg").style.display = 'none';

}

and HTML:

<body onload="callFunction();">
  <label id="lblmsg"></label>

 </body> 

2 answers

3

If you only need to "hide" the content of the site before the load be fired, can use a class with this property that is inserting directly into the DOM, it is easier to manipulate:

.hide { display: none }

The content to be "hidden" while the page is loaded may initially have that class. Simply remove it when the load is fired.

ps: I put an image for the load to take to be fired on a first load.

var loading = document.querySelector('div'),
    content = document.querySelector('main');

window.onload = function() {
  loading.classList.add('hide');    // esconde o 'carregando'.
  content.classList.remove('hide'); // mostra o conteúdo do site.
};
.hide, img { display: none }
<div>
  <p>carregando...</p>
</div>

<main class='hide'>
  <img src='http://i.stack.imgur.com/uoKIw.jpg' />
  conteúdo do site.
</main>

In the above example I used classList but I already say that not all browsers have this feature implemented. Internet Explorer < 10 and Opera Mini 5 do not support the classList - see browsers that support. Anyway in that reply there are possible solutions you can use.


If you want to display a progress bar as the site loads (showing the percentage), I suggest using the PACE for this.

2

Do it this way:

<body>
  <label id="lblmsg">Carregando...</label>
 </body>

<script>
window.onload = callFunction;
</script>

In that case, window.onload causes this function to be executed after the entire page has been loaded.

It’s best to leave all the coding in one tag script or in a arquivo javascript. Makes it easier to maintain code.

And I think in that case, the best choice is to leave the word Carregando... within the label#lblmsg and then when the contents are loaded, hide it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.