How to make a preloader before web page even loaded?

user2002495 picture user2002495 · Oct 9, 2013 · Viewed 10.9k times · Source

I'd like to make a preloader bar that shows how much the page is loading before it is fully loaded (something like pushcollective.com, notice the upper bar before the page is fully load).

How can I achieve something like this? I imagine directing the user into a loading page first and request the page using AJAX and put the requested content into a div after it has finished loading. But I don't think that's a clean solution?

Answer

matewka picture matewka · Oct 9, 2013

The website you provided a link to (http://pushcollective.com/) uses NProgress.js plugin. As far as I was able to explore it uses random values to increment the progress bar (IMHO not a very elegant solution but I guess the only possible).
Here is a snippet from plugins code:

/**
 * Increments by a random amount.
 */

  NProgress.inc = function(amount) {
    var n = NProgress.status;

    if (!n) {
      return NProgress.start();
    } else {
      if (typeof amount !== 'number') {
        amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95);
      }

      n = clamp(n + amount, 0, 0.994);
      return NProgress.set(n);
    }
  };