bart2puck
bart2puck

Reputation: 2522

Jquery loading div before page starts actually loads

I have a page that has to do quite a bit of work (5-6 seconds) of loading data from all over the place on the initial connection. It is slow because of the api endpoints I am calling, I have no control over it.

Is there a way to get a loading div to show before it starts doing all of its data collection?

The below doesnt do anything. I believe its because the page already starts gathering data before it gets to the jquery. I could be wrong. myjs.js is the file name and it is the first thing loaded on my page.

$('body').on('load', function(){
    $body.addClass("loading");
});

and does the same thing

  $(document).ready(function() {
      $body.addClass("loading");
   });

In layman's terms:

  1. User goes to https://somewebsite.com
  2. Jquery loading div shows
  3. other functions run to gather data
  4. jquery loading div is removed.

This is in the laravel framework if that affects anything.

Upvotes: 1

Views: 85

Answers (1)

Voorie
Voorie

Reputation: 71

There is actually a pretty simple way to do this. I recently experienced something similar.

I did something like this:

window.addEventListener('load', (event) => {
  setTimeout(() => {
    $('.jumping-dots-loader').slideUp(650);
  }, 1000);
});
.jumping-dots-loader {
  width: 100vw !important;
  height: 100vh !important;
  background-color: white;
  z-index: 99999999999999999999999;
  display: block;
  border: none;
  border-radius: 0;
  margin: 0;
  position: fixed;
  padding: 20% 35%;
  text-align: center;
}

.jumping-dots-loader span {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 100%;
  background-color: rgba(147, 194, 61, 1);
  margin: 35px 0.85rem;
}


/* Add in animation */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="jumping-dots-loader">
  <span></span>
  <span></span>
  <span></span>
</div>

<h1>
  Howsit going?
</h1>

If you go through Mozilla's docs about the document.readystatechange event, you will see how the browser handles the loading order and can use this to your advantage. In my example, I add a container div which will cover the user's viewport. Then style some dots (add your own animation to them) which will be displayed while the document is loading. When the load state is reached, the placeholder div will be hidden and the loaded page is displayed.

Upvotes: 1

Related Questions