Introducing nprogress
nprogress
is a minimalist JavaScript library that provides a visual progress bar at the top of the page. It is commonly used to indicate loading states in web applications, enhancing user experience by providing feedback about ongoing background processes.
APIs and Usage
1. Start
The NProgress.start()
method is used to initiate the progress bar.
NProgress.start();
2. Done
The NProgress.done()
method is employed to finish the progress bar, typically after an async operation is complete.
NProgress.done();
3. Inc
The NProgress.inc()
method increments the progress by a little.
NProgress.inc();
4. Set
The NProgress.set()
method sets the progress to a certain value, between 0 and 1.
NProgress.set(0.5); // Sets the progress bar to 50%
5. Configure
The NProgress.configure()
method allows for configuration of the progress bar.
NProgress.configure({ ease: 'ease', speed: 500 });
Advanced Usage Example
Let’s build a simple web app to demonstrate nprogress
APIs in action.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css"> <title>nprogress Demo</title> </head> <body> <button onclick="loadData()">Load Data</button> <div id="content"></div> <script> function loadData() { NProgress.start(); fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()) .then(data => { document.getElementById('content').innerHTML = JSON.stringify(data, null, 2); NProgress.done(); }) .catch(error => { console.error('Error fetching data:', error); NProgress.done(); }); } </script> </body> </html>
This example demonstrates how to show a progress bar while fetching data from an API endpoint.
Hash: 6d836cb3bcee16723702e7ba14e788771ed5f1416ab47471de6572ad633192ae