NProgress.js to show progress of page loading

Aaron picture Aaron · Sep 11, 2013 · Viewed 27.6k times · Source

I am trying to figure out how to use NProgress.js as a generic page load for all pages on a site. I am unable to find any documentation or an easy way to add this loading effect on page load and have it finish when the entire page has loaded.

http://ricostacruz.com/nprogress/

Any help is greatly appreciated!

Answer

Nabil Kadimi picture Nabil Kadimi · Feb 26, 2014

Simply put, place this JavaScript anywhere in your html, it's a good practice to place it before the closing body tag:

<script>

    // Show the progress bar 
    NProgress.start();

    // Increase randomly
    var interval = setInterval(function() { NProgress.inc(); }, 1000);        

    // Trigger finish when page fully loaded
    jQuery(window).load(function () {
        clearInterval(interval);
        NProgress.done();
    });

    // Trigger bar when exiting the page
    jQuery(window).unload(function () {
        NProgress.start();
    });

</script>

Oh and don't be confused, NProgress is in the global scope, it has nothing to do with jQuery, I'm using jQuery's .load()/.unload() for convenience only, and please don't put the NProgress.start() inside a jquery document's .ready(), it's useless clutter.