0

Hy I would like to build a load bar when my site is loading.

To do it I need to know how to get the entire file size witch must be loaded and the actual file size witch has already been loaded, to do it I would like to use only JS.

  • Welcome to SO - please show what you've tried – StudioTime Aug 09 '17 at 13:45
  • What file are you loading and how are you loading it? Your JS won't run until the page has already been loaded. –  Aug 09 '17 at 14:01
  • Possible duplicate of [How to show a running progress bar while page is loading](https://stackoverflow.com/questions/18981909/how-to-show-a-running-progress-bar-while-page-is-loading) – Liam Aug 09 '17 at 14:06

1 Answers1

1

This is going to be much more work than is worth doing.

In order for your site to display a progress bar, it will have to have already loaded the code necessary for displaying the progress bar -- and by that point you no longer need a progress bar, because the site has already loaded.

You could, in theory, have your site first load a splash screen which exists only to load the actual website via AJAX calls and display the progress bar. That splash screen would have to check the Content-Length header of each file to be downloaded (though not all servers report this accurately; some always return "0"), and then poll the XHR "progress" event to calculate how much has been downloaded already. Finally, once all the necessary files are downloaded you'd have to bootstrap your way into displaying the actual site -- I think that so long as they're all static files you should be able to just redirect to the files you would have normally loaded in the first place, and the browser will still have them in cache so won't re-download them, but I'm not 100% certain of that.

As you can see, that'd be a pain to implement, and would effectively make your website slower because of the time spent downloading the splash screen code instead of the thing the user actually wanted.

Instead, consider loading your site normally, isolating the parts that are slow to download, and putting progress bars on just those particular elements (using the same XHR techniques as described above.) This is easier if you build your site using a clientside SPA framework such as React, Vue, or Angular, though you of course then have the additional overhead of the framework itself to contend with.

UPDATE: looking at the answers to the possible duplicate of this question linked above, I notice a plugin named PACE.js that purports to automate some of this (it appears to work by detecting any ajax calls in progress, and watching for specific defined page elements as a signal that the loading is complete.) If close enough is close enough, that may be a simple drop-in worth experimenting with.

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53