Sometimes, we want to display a loading bar before the entire page is loaded with JavaScript.
In this article, we’ll look at how to display a loading bar before the entire page is loaded with JavaScript.
Display a Loading Bar Before the Entire Page is Loaded with JavaScript
To display a loading bar before the entire page is loaded with JavaScript, we can watch for the load
event with jQuery.
When the load
event is emitted, we remove the loading indicator from the screen.
To do this, we write:
<div id="overlay">
<img src="https://c.tenor.com/I6kN-6X7nhAAAAAj/loading-buffering.gif" alt="Loading" />
Loading...
</div>
to add the loading indicator.
Then we write:
$(window).on('load', () => {
$('#overlay').fadeOut();
});
to watch the load
event with the on
method.
Then we call fadeOut
on the div to remove it from the screen with a fade-out effect.
Conclusion
To display a loading bar before the entire page is loaded with JavaScript, we can watch for the load
event with jQuery.
When the load
event is emitted, we remove the loading indicator from the screen.