Reputation:
I'm using jQuery to modify the style of some pages in a large set of existing Web pages. This works, but the problem I have is that, for longer pages, the page is briefly visible with the wrong styles before the javascript kicks in and transforms the page.
I'm using this kind of thing (the alerts are just to emphasize the problem):
$(document).ready(function(){ ... alert("at this point the page is visible unstyled"); $('body').addClass('myStyle'); alert("now page looks like I want it to"); ... }
How do I prevent the browser from displaying the page until $(document).ready(function() completes?
EDIT
Note: I can't change the HTML of the pages (they're not mine). All I can do is swap in a replacement JavaScript file and work with what's already in the HTML
Upvotes: 0
Views: 1306
Reputation: 4967
If you don't have any AJAX, the following is sufficient:
(before the <body>
tag)
body {
display: none;
}
(after jQuery library is loaded)
$(document).ready(function(){
// Other code here
$('body').css('display', 'inline');
}
But hiding the body until loading is complete is sometimes even more useful when you do have AJAX, so the above is not sufficient.
Javascript executes code sequentially, but won't wait for asynchronous tasks to complete before moving on. So, if the code you replace the // Other code here
placeholder with is asynchronous, the body will be displayed before it completes, which defeats the purpose of hiding the body.
One way you could overcome that is to utilise a callback function. For example, you can use .always
as part of AJAX:
$('body').css('display', 'none');
$(document).ready(function(){
$.ajax(
// AJAX of some sort e.g. loading a Google Map.
).always(function() {
$('body').css('display', 'inline');
});
}
The .always
handler function won't execute until the AJAX has been attempted.
It doesn't end with AJAX though, I'd recommend you look into the deferred object.
Upvotes: 0
Reputation: 1449
var blanky = document.createElement("div");
blanky.style.width = "100%";
blanky.style.height = "100%";
blanky.style.position = "absolute";
blanky.style.top = "0px";
blanky.style.left = "0px";
blanky.style.backgroundColor = "white";
blanky.id = "blanky";
document.body.appendChild(blanky);
Now after you loaded all your stuff, do this;
document.getElementById("blanky").style.display = "none";
Do this stuff as soon as the body element is loaded. If your script is inside the body element anyway, don't append any events. If it's in head, you should use the ready event for example.
This also allows you to put virtually anything into the div, say, a loading screen for example!
Upvotes: 0
Reputation: 9888
Wrap everything with <div id="wrap" style="display: none"></div>
and then at the end of your domReady
handler put $('#wrap').css('display', '');
In case you can not change HTML, try this in your script:
$('body').css('display', 'none');
$(document).ready(function(){
...
$('body').css('display', '');
}
Upvotes: 2