jQuery Fade in Site/Content Once It's Loaded?

Jezthomp picture Jezthomp · Nov 10, 2011 · Viewed 51.2k times · Source

Are there any tutorials or plugins for fading a site into view once its loaded properly, to limit any jarring etc, so the content appears smoothly basically?

I suppose it would be easier if it was just a specific area, as a header or footer will already be cached, from previous pages...

For example a portfolio page with various thumbnails, they only appear smoothly when ready.

Can this be done?

Thank you for any help :)

Answer

T.J. Crowder picture T.J. Crowder · Nov 10, 2011

First, a side point: In general, web designers spend a lot of time trying to improve perceived page load time, getting things shown as quickly as possible. This actively goes the other way, presenting a blank page until everything is ready, which may not be ideal.

But if it's appropriate for your situation:

Since everything visible will be a descendant of body, you could load body hidden and then fade it in. It would be important to include a fallback for users without JavaScript (typically fewer than 2% at least according to Yahoo, but still). So along the lines of:

(Live Copy)

<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<!-- This next would probably be in your main CSS file, but shown
     inline here just for purposes of the example
-->
<style type="text/css">
body {
    /* Hide it for nifty fade-in effect */
    display: none;
}
</style>
<!-- Fallback for non-JavaScript people -->
<noscript>
<style type="text/css">
body {
    /* Re-displays it by overriding the above */
    display: block;
}
</style>
</noscript>
</head>
<body>
...content...
<script src="jquery.js"></script>
<script>
// This version runs the function *immediately*
(function($) {

  $(document.body).fadeIn(1000);

})(jQuery);
</script>
</body>
</html>

A couple of variations on the script part of that, depending on when you want the fade-in to occur:

Wait for "ready" event:

Live Copy

// This version waits until jQuery's "ready" event
jQuery(function($) {

  $(document.body).fadeIn(1000);

});

Wait for the window#load event:

Live Copy

// This version waits until the window#load event
(function($) {

  $(window).load(function() {
    $(document.body).fadeIn(1000);
  });

})(jQuery);

window#load fires very late in the page load process, after all external resources (including all images) have loaded. But you said you wanted to wait until everything was loaded, so that might be what you want to do. It will definitely make your page seem slower...