SpyFox
SpyFox

Reputation: 17

Measure loading time in Jquery

I have a question about a Javascript-file I've made. It makes sure hyperlinks open in a div and not in a new tab. However, I've also made a very simple text-inclusion to show while the page is loading.

    $(document).ready(function () {
    $('a').on('click', function(e){
        e.preventDefault();
        var page_url = $(this).prop('href');
        var loading = 
        $('#content')
        .html('<h2>The page is loading. A second please.</h2>')
        .load(page_url);
    });
});

However, some pages are considerably loading faster than others. In other words, in some pages it's very useful to have this script, but when a page is loading immediately, it's just simply very annoying.

Is it possible to measure the time that the 'load' takes, and accordingly, display html or not? (I was thinking about something like: "If time-loading>1000 .html('blabla') / Else").

Upvotes: 1

Views: 308

Answers (2)

SpyFox
SpyFox

Reputation: 17

For fellow googlers, I combined the comments and the answer above to provide a solution. What I did was the following: instead of not displaying the loading message if the page was loading within a second, I made sure it was at least displaying at least a second:

$(document).ready(function () {
$('a').on('click', function(e){
    e.preventDefault();
    $('#content').html("<div id='status' class='status'></div>");
    $('#status').html('<h2>The page is loading. A second please.</h2>');
    var page_url = $(this).prop('href');
    var loadingMsg = setTimeout(function(){
            $('#content').load(page_url, function (){
                clearTimeout(loadingMsg);
                $('#status').html();
            });
        },1000);
    });
});

The reasons why I did this, is because I couldn't get the timeout-function consistent. Sometimes it worked perfectly, but sometimes the screen just froze and nothing was displayed until the page loaded. Now, it is displayed at least a second, and if the loading takes more, it will be displayed until the page loads. Thanks for your answers and I hope this helps for people with a similar problem!

Upvotes: 0

Maurice Perry
Maurice Perry

Reputation: 32831

You can do something like that:

var timer = setTimeout(function() {
    $('#content').html('<h2>The page is loading. A second please.</h2>');
    timer = null;
}, 1000);
$('#content').load(page_url, function() {
    if (timer) {
        clearTimeout(timer);
    }
});

Upvotes: 1

Related Questions