112

Is there a way to detect when a page has finished loading ie all its content, javascript and assets like css and images?

so like:

if(PAGE HAS FINISHED LOADING)
{
// do something amazing
}

and also additionally if the page has been loading for more than 1 min then do something else such as:

if(PAGE HAS BEEN LOADING FOR 1 MIN)
{
// do something else amazing
}

I've seen websites like Apple's MobileMe do similar checks but haven't been able to figure it out in their huge code libraries.

Can anyone help?

Thanks

EDIT: This is essentially what I want to do:

// hide content
$("#hide").hide();

// hide loading
$("#loading").hide();

// fade in loading animation
setTimeout($('#loading').fadeIn(), 200);

jQuery(window).load(function() {
  $("#hide").fadeIn();

  $("#loading").fadeOut(function() {
    $(this).remove();
    clearInterval(loadingAnim);
  });

  setTimeout(function() {
    $("#error").fadeIn();
  }, 60000);
});
Nope
  • 22,147
  • 7
  • 47
  • 72
Cameron
  • 27,963
  • 100
  • 281
  • 483

10 Answers10

142
jQuery(window).on("load", function () {
    alert('page is loaded');

    setTimeout(function () {
        alert('page is loaded and 1 minute has passed');   
    }, 60000);

});

Or http://jsfiddle.net/tangibleJ/fLLrs/1/

See also http://api.jquery.com/load-event/ for an explanation on the jQuery(window).load.

Update

A detailed explanation on how javascript loading works and the two events DOMContentLoaded and OnLoad can be found on this page.

DOMContentLoaded: When the DOM is ready to be manipulated. jQuery's way of capturing this event is with jQuery(document).ready(function () {});.

OnLoad: When the DOM is ready and all assets - this includes images, iframe, fonts, etc - have been loaded and the spinning wheel / hour class disappear. jQuery's way of capturing this event is the above mentioned jQuery(window).load.

Zvika
  • 1,236
  • 12
  • 16
T. Junghans
  • 11,385
  • 7
  • 52
  • 75
  • If you look at my OP I have amended it so that it shows what my aims are. So essentially I want to show the page after all assets have loaded and fade out a loader and fade in the content. Would my code work correctly? Cheers – Cameron Aug 16 '11 at 19:36
  • Your code looks alright but I'd have to see it in action to be sure. – T. Junghans Aug 16 '11 at 19:43
  • @Jimmer Yes: [MDN](https://developer.mozilla.org/en-US/docs/Web/Events/load): _"The load event is fired when a resource and its dependent resources have finished loading."_ – T. Junghans Mar 11 '15 at 14:28
  • 8
    Please note that `jQuery.load()` was deprecated since jQuery/1.8 and removed in jQuery/3. Current syntax is `jQuery(window).on("load", function(){/*...*/});`. – Álvaro González Jul 24 '18 at 07:42
64

there are two ways to do this in jquery depending what you are looking for..

using jquery you can do

  • //this will wait for the text assets to be loaded before calling this (the dom.. css.. js)

    $(document).ready(function(){...});
    
  • //this will wait for all the images and text assets to finish loading before executing

    $(window).load(function(){...});
    
Jahan Zinedine
  • 14,616
  • 5
  • 46
  • 70
samccone
  • 10,746
  • 7
  • 43
  • 50
  • In this method, how can you tell if the page has been loading for several minutes but is not yet complete? – yoozer8 Aug 16 '11 at 19:30
  • 2
    this can be accomplished with a setTimeout(function(){ !loaded && foo();},20000); and set loaded to true in the doc ready or window load – samccone Jun 12 '12 at 13:40
  • 2
    for jquery 3.0 use $(window).on("load", function (e) { }); – zero8 Sep 19 '17 at 05:26
17

That's called onload. DOM ready was actually created for the exact reason that onload waited on images. ( Answer taken from Matchu on a simmilar question a while ago. )

window.onload = function () { alert("It's loaded!") }

onload waits for all resources that are part of the document.

Link to a question where he explained it all:

Click me, you know you want to!

Community
  • 1
  • 1
Nemanja
  • 1,505
  • 12
  • 24
  • The problem with onload is that if I do `window.onload = function(){...}` when the page is already loaded nothing happens. Is there a way to get around that? – Donald Duck Aug 14 '21 at 10:49
10

Another option you can check the document.readyState like,

var chkReadyState = setInterval(function() {
    if (document.readyState == "complete") {
        // clear the interval
        clearInterval(chkReadyState);
        // finally your page is loaded.
    }
}, 100);

From the documentation of readyState Page the summary of complete state is

Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • I've been having issues with cached images, and this seems to be the better code for that in performance... Wondering about practice? Seems to be better than the jQuery `$(window).on("load" function () {//dostuff})`...? – kmkmkm Jun 14 '17 at 21:18
10

I think the easiest way would be

var items = $('img, style, ...'), itemslen = items.length;

items.bind('load', function(){ 
    itemslen--;
    if (!itemlen) // Do stuff here
});

EDIT, to be a little crazy:

var items = $('a, abbr, acronym, address, applet, area, audio, b, base, ' + 
    'basefont, bdo, bgsound, big, body, blockquote, br, button, canvas, ' + 
    'caption, center, cite, code, col, colgroup, comment, custom, dd, del, ' +
    'dfn, dir, div, dl, document, dt, em, embed, fieldset, font, form, frame, ' +
    'frameset, head, hn, hr, html, i, iframe, img, input, ins, isindex, kbd, ' +
    'label, legend, li, link, listing, map, marquee, media, menu, meta, ' +
    'nextid, nobr, noframes, noscript, object, ol, optgroup, option, p, ' +
    'param, plaintext, pre, q, rt, ruby, s, samp, script, select, small, ' + 
    'source, span, strike, strong, style, sub, sup, table, tbody, td, ' + 
    'textarea, tfoot, th, thead, title, tr, tt, u, ul, var, wbr, video, ' + 
    'window, xmp'), itemslen = items.length;

items.bind('load', function(){ 
    itemslen--;
    if (!itemlen) // Do stuff here
});
qwertymk
  • 34,200
  • 28
  • 121
  • 184
6

FYI of people that have asked in the comments, this is what I actually used in projects:

function onLoad(loading, loaded) {
    if(document.readyState === 'complete'){
        return loaded();
    }
    loading();
    if (window.addEventListener) {
        window.addEventListener('load', loaded, false);
    }
    else if (window.attachEvent) {
        window.attachEvent('onload', loaded);
    }
};

onLoad(function(){
   console.log('I am waiting for the page to be loaded');
},
function(){
    console.log('The page is loaded');
});
Cameron
  • 27,963
  • 100
  • 281
  • 483
3

One option is to have the page be blank, containing a small amount of javascript. Use the script to make an AJAX call to get the actual page content, and have the success function write the result over the current document. In the timeout function you can "do something else amazing"

Approximate pseudocode:

$(document).ready(function(){
    $.ajax
      url of actual page
      success:do something amazing
      timeout: do something else
});
yoozer8
  • 7,361
  • 7
  • 58
  • 93
  • Yes, it is. But it's the first way that came to mind when I asked myself "How can a page tell if a request for it times out?" – yoozer8 Aug 16 '11 at 19:22
  • well it will not tell you if the images have finished loading.. rather it will only say if the raw markup has been loaded – samccone Aug 16 '11 at 19:23
  • Hm. Leads me to an interesting question. If you just did $(document).html(response), and response contained a document.ready or a window.load, would that execute once the document is written? Or would the browser see the page as already loaded and not call them on the content change? – yoozer8 Aug 16 '11 at 19:25
  • i think it will call it a second time but not 100% ... try it out – samccone Aug 16 '11 at 19:27
2

Without jquery or anything like that beacuse why not ?

var loaded=0;
var loaded1min=0;
document.addEventListener("DOMContentLoaded", function(event) {
   loaded=1;
    setTimeout(function () {
      loaded1min=1;
    }, 60000);
});
Cth103
  • 63
  • 5
  • 1
    This is correct, but slightly different from what `jquery` performs. `DOMContentLoaded` is triggered only after external content is loaded (notably images, which can take a long time in certain conditions). `jquery` performs `.ready()` using browser specific events, which (on most browsers) happen before external content is loaded. – grochmal Jun 22 '16 at 22:51
2

Is this what you had in mind?

$("document").ready( function() {
    // do your stuff
}
John Smith
  • 43
  • 1
  • 4
1
var pageLoaded=0;

$(document).ready(function(){
   pageLoaded=1;
});

Using jquery: https://learn.jquery.com/using-jquery-core/document-ready/

ShawnDaGeek
  • 4,145
  • 1
  • 22
  • 39
Danial
  • 1,496
  • 14
  • 15