Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, display loading page div only if the page takes more than 2 seconds to load

This is my first question, so hopefully I will give enough details. I have the following code in 4 pages on a website:

$(document).ready(function() {
  $('#page_loading').slideDown(500);
});

jQuery(window).load(function () {
  setTimeout(function() {$('#page_loading').slideUp(500);}, 1500);
});

What I am I trying to achieve: When browsing thorough the 4 pages, have the #page_loading div slide down only if the page takes more than 2 seconds to load. If the pages takes less than 2 seconds to load (was visited before and most of the images are cached) then the loading div won't show up.

At this point, even if the page takes less than one second to load that loading div still appears and disappears, and it's pretty annoying.

Thank you, Cristian.

like image 628
Cristian Serban Avatar asked Oct 22 '22 16:10

Cristian Serban


1 Answers

Will this do the trick?

var showTimeout = setTimeout(function() {
    $('#page_loading').slideDown(500);
}, 2000);

jQuery(window).load(function () {
    clearTimeout(showTimeout);
    $('#page_loading').slideUp(500);
});
like image 194
sroes Avatar answered Nov 02 '22 08:11

sroes