Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding everything until the page has finished loading

Tags:

jquery

I am looking to have everything on my page hidden until the page has finished loading. I have seen many posts and tried different things. The most common solution which works great is

<body style="display:none;">

Then run jQuery to show it again upon window load

$(window).load(function() {
  $("body").fadeIn("slow");
});

I have an issue with this, as the page is reliant on JS to show anything at all. I appreciate this is a rare thing, but just feels wrong.

Ideally I would like to use jQuery to add the display:none css as well

however...

The problem is when I add

$(document).ready(function {
  $(body).css('display', 'none');
});

Even this takes a while to run and the page flickers with content before hand.

Is there a better way?

Could I use the above script without document.ready (tried, but didn;t work)

Thanks.

like image 434
Pete Norris Avatar asked Feb 28 '14 12:02

Pete Norris


People also ask

How to hide a div when a page is loaded?

Use display none on the element eighter in HTML, or in CSS files. Attribute hidden is also helpful.

How to hide content on page load in jQuery?

$(document). ready(function() { $('#example'). hide(); }); This may be a fairly obvious way to do this but it's not particularly ideal; the element will be displayed on the page until the page has finished loaded and will then hide.

How do I hide a button on page load?

Set the html button style attribute to display none. Then in document ready function show the button.

How to hide an element in JavaScript on page load?

Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery. To hide an element, set the style display property to “none”. document. getElementById("element").


2 Answers

To hide it using javascript, set script just after BODY tag declaration:

<body>
    <script>document.body.style.display = "none";</script>

This way if javascript disabled, BODY is still shown

like image 144
A. Wolff Avatar answered Sep 19 '22 14:09

A. Wolff


The approach I use it to have a js class and a hidden-until-ready class. My hidden until ready styles are only applied if there is a js class.

e.g

.js .hidden-until-ready {
    visibility: hidden;
}

the js class is applied at the start if JavaScript is enabled.

document.documentElement.className = document.documentElement.className + ' js';

Then in jQuery I remove the hidden-until-ready once the page has loaded.

jQuery(document).ready(function () {
    jQuery('.hidden-until-ready').removeClass('hidden-until-ready');
});

This way the elements of the page are only hidden at the start if JavaScript is enabled and once the page has loaded the elements are visible again.

like image 32
Colin Bacon Avatar answered Sep 18 '22 14:09

Colin Bacon