</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/68485/how-to-show-loading-spinner-in-jquery" dir="ltr">How to show loading spinner in jQuery?</a>
<span class="question-originals-answer-count">
(24 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2019-08-19 06:19:43Z" class="relativetime">8 months ago</span>.</div>
</div>
</aside>
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.
</div>
Here is a solution that:
$("#loader").show()
$("#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();
}
});
});
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