0

my page slows down every time I run my script, that's why I need to know how I can fix it

I have tried it on my local and public server and I have the same slow loading problem.

<script type="text/javascript" src="catalog_rank3.js"></script>

<form action="javascript:;" onsubmit="setSceneProducts()">
    <input type="text" class="btn-transparent" id="hov" size="50" placeholder="Link Here"><br/><br/>
    <span class="btn-border btn-primary">
        <input type="submit" class="btn btn-primary btn-lg" value="Unhide">
    </span>
</form>

<div id="main">result here</div> 

I would like to know if I can add a loader so that the data is displayed when the entire load is complete.

spawn
  • 1
  • 1

2 Answers2

0

Here is a solution that:

  • on button click, shows a div containing an image using $("#loader").show()
  • emulates a server delay of 3 seconds
  • hides the div containing the image using $("#loader").hide()

Several websites provide "loading ajax gifs" - download one and reference it in <img>.

The jsFiddle link is here.

Here is another version that shows the loader image in a modal that "hides" the whole page.

HTML

<div class="container">
  <button id="button1" type="button">click me</button>
  <div id="loader"><img src="https://picsum.photos/200"></div>
</div>

CSS

#loader {
  display: none;
}

JS

$(document).on("click", "#button1", function() {

  // show the loader 
  $("#loader").show();
  /* 
   BEGIN mockjax
   this just imitates ajax behaviour in this demo 
   see:  https://github.com/jakerella/jquery-mockjax
   */
  $.mockjax({
    url: `/path/to/your/file`,
    responseTime: 3000, // mimic a delay of 3 seconds for this demo  
    response: function(settings) {
      response = {
        status: "great!",
        message: "everything is good!"
      };

      this.responseText = JSON.stringify(response);
    }
  });
  // END mockjax - this just imitates ajax behaviour in this demo 

  $.ajax({
    url: `/path/to/your/file`,
    data: {
      "key1": "val1"
    }, // send the parameters to your server side file
    type: "POST",
    success: function(response) {
      // hide the loader
      $("#loader").hide();
    }
  });

});
user1063287
  • 10,265
  • 25
  • 122
  • 218
0

I recommend using Promises if you have multiple asynchronous calls. You can show a loader(gif) on initialization and when all data is fetched i.e. all promises get resolved, you can hide the loader. Reference link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Usman Saeed
  • 211
  • 1
  • 8