NProgress
Learn how to add a progress bar to your website. In this tutorial, I will use Vite.
Install package
Install a main package for progress bar.
npm install nprogress
Setup NProgress
Custom NProgress stylesheet
Create a new CSS file. We will custom some CSS to override default style.
I don't RECOMMEND you to add default NProgress stylesheet.
We will copy (almost) all styles and add some slightly changes because some styles were written date back to 2014!
Replace with this shorter stylesheet.
:root {
--color-primary: #29d; /* change your color here */
}
#nprogress {
pointer-events: none;
}
#nprogress .bar {
z-index: 1031;
background: var(--color-primary);
width: 100%;
height: 2px;
position: fixed;
top: 0;
left: 0;
}
#nprogress .peg {
opacity: 1;
width: 100px;
height: 100%;
display: block;
position: absolute;
right: 0;
transform: rotate(3deg) translate(0, -4px);
box-shadow: 0 0 10px var(--color-primary), 0 0 5px var(--color-primary);
}
Import JavaScript file
Import package and css to your main JavaScript file. Add some basic configurations.
import './styles/custom-nprogress.css';
import NProgress from 'nprogress';
// Configuration
NProgress.configure({
showSpinner: false,
});
Then initiate the NProgress.start() and NProgress.done(). We want it to be finish after loading finish. We must ust window.onload or addEventListener
// Start
NProgress.start();
// End
window.addEventListener('load', function () {
NProgress.done();
});
Delay disappearance
NProgress will vanish immediately when page is loaded successfully. We will add delay with setTimeOut()
// Start
NProgress.start();
// End
window.addEventListener('load', function () {
setTimeOut(function () {
NProgress.done();
}, 1000);
});
It means if page is successfully loaded, NProgress will be disappeared 1 second later. You can try with different time and see the result.
Final code
import './styles/custom-nprogress.css';
import NProgress from 'nprogress';
NProgress.configure({
showSpinner: false,
});
NProgress.start();
window.addEventListener('load', function () {
setTimeOut(function () {
NProgress.done();
}, 1000);
});
Artificial delay (optional)
Let's build an artificial delay to simulate the fetching.
import './styles/custom-nprogress.css';
import NProgress from 'nprogress';
NProgress.configure({
showSpinner: false,
});
NProgress.start();
async function fetchSomething(timeInSecond: number): Promise<void> {
return new Promise(function (resolve) {
setTimeout(resolve, timeInSecond * 1000);
});
}
window.addEventListener('load', async function () {
await fetchSomething(3); // Example: waits for 3 seconds 2G network
setTimeout(function () {
NProgress.done();
}, 200);
});
Once you finish your experiment, revert to the normal code.
References
- NProgress https://github.com/rstacruz/nprogress
- NProgress CSS stylesheet https://github.com/rstacruz/nprogress/blob/master/nprogress.css