2
votes

I want to hide a spinner div once ALL elements are loaded and in position on my page. I put a fadeOut() function on my spinner div in the window.on('load', ..., but I can see the tab/page is still loading even though the elements/assets are not in the correct css position yet. How do I force the spinner div to remain until everything is in place, i.e. until the loading icon on the tab is finished spinning?

This is my code:

$(window).load(function() {
 $('#spinner').fadeOut();
}

jQuery(document).ready(function($){
 // Append the spinner div.
 $("#spinner").append(spinner.el);
}
1
have you tried promise ? - Don
Which kind of element is still loading? Can you ate least post a minimalistic sample replicating your issue? - A. Wolff
@A.Wolff It seems to be that images etc are loading, but there's lots of css with absolute positioning (I need it for scrollMagic, the plugin I'm using) so while I can see that the images are loaded, they aren't in place yet. So they are in a mess on the page, until they jump into their correct positions, so I want to hide this from the user until it's all sorted in place. - Rebecca O'Riordan
@Don I haven't, I've never used a promise before. How would that work? - Rebecca O'Riordan
A timeout is for sure not a solution. You'd have better to debug your code until you spot what's going wrong. And i suspect this has nothing to do with load event being fired too early - A. Wolff

1 Answers

1
votes

It sounds like you have a large volume of CSS and it is taking a long time for the browser to compute the style for each element after all content for the page has loaded. You could do some experiments using your timeout idea, and polling one or more elements on the page to see when the computed style matches the expected style. The last element to be assigned a computed style might vary at each page load, and/or by browser, so you would definitely need to test your method. The example below uses some information from the accepted answer here to poll an element for an expected style.

var expectedTop="5px";

function ready() {
    $('#spinner').fadeOut();
}

function poll() {
    var o = document.getElementById("pollElementId");
    var comp = o.currentStyle || getComputedStyle(o,null);
    if(comp.top==expectedTop) {
        ready();
    }
    else {
        setTimeout("poll()",500);
    }
}

jQuery(document).ready(function($){
    $("#spinner").append(spinner.el);
    poll();
}

Here pollElementId is the id of an element in the DOM that we are positioning via CSS.