Add Youtube like loading bar on your website

Everyone notices Youtube loading bar on top of their video pages, it indicates page is loading and which actually looks pretty cool. Today I will show you how you can quickly add Youtube like progress bar on our website. Go to Github and download nprogress Javascript plugin or just point to nprogress CDN here, it is particularly made for Ajax web application but you can do other things with it too. All we need is nprogress.js and nprogress.css from the repo.

Step 1

Add nprogress.js and nprogress.css to your projects.
JS
  • 1
  • 2
<script src='https://cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js'></script> <link rel='stylesheet' href='ttps://cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css'/>

Step 2

Nprogress offers two methods NProgress.start() and NProgress.done(), we will incorporate them with DOM document.readyState property, it tells us the loading status of the current document. That's it! Just put the following code at the bottom of your page but before </body> tag and you should see it in action.
JS
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
//Page is loading start progress document.onreadystatechange = function () { if (document.readyState == "interactive") { NProgress.start(); //start progress bar } } //when page is loaded stop progress var everythingLoaded = setInterval(function() { if (/loaded|complete/.test(document.readyState)) { clearInterval(everythingLoaded); setTimeout(function(){NProgress.done()},2000); } }, 10);
Here's jQuery version if you are using jQuery:
JS
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
$(document).ready(function() { NProgress.start(); }); $(window).load(function() { //setTimout() for 2 seconds progress stop delay setTimeout(function(){NProgress.done()},2000); });

Wrap Up

Trick is simple, NProgress.start() automatically starts the progress increment, and when page is loaded we simply call NProgress.done().

Demo

Did you notice loading bar at the top of this page? try reloading this page to see it in action.
New question is currently disabled!