Remote JavaScript includes without the performance penalty (part 2)

In part 1 I showed you how to speed up page rendering by moving a remote JavaScript include (a Flickr badge in the example) into a hidden <div> at the bottom of the page and using a few lines of code to drop it into the desired location once it it's loaded. In this article, I'll show you how to use the Yahoo! UI Library's Animation Utility to make your dynamically-loaded content fade in smoothly so your visitors aren't distracted by its sudden appearance.

First we need to load the YUI libraries. To do this, we'll add the following lines just above our hidden "fakeflickr" <div> from part 1:

<script src=""></script>
<script src=""></script>

<div id="fakeflickr" style="display: none;">
  <script src="[...]"></script>

This will load the necessary libraries from Yahoo!'s own servers, which are so fast I heard they once did the Kessel Run in less than twelve parsecs.

Next, we'll need to add a teeny bit of CSS to give our "flickr" <dd> element a fixed height. This will keep the page layout from having to adjust when we populate that element with the Flickr badge content.

To figure out what height you should use, I recommend using Firebug to inspect the element and see what its height is once the badge is loaded. Then use that number in the CSS below, which you can either put inside a <style> tag in the page header or add to an external CSS file:

#flickr {
  background: url('loading.gif') no-repeat 48% 48%;
  height: 161px;

Notice the background image? You can grab that from It'll clue our visitors into the fact that the content in that area is being loaded in the background, so they'll be less surprised when they see it fade in.

Now all we need to do is make a few modifications to our JavaScript snippet from part 1 to make the Flickr badge fade in:

<script type="text/javascript">
  var flickr     = document.getElementById('flickr'),
      fakeflickr = document.getElementById('fakeflickr'),
      anim       = new YAHOO.util.Anim(flickr, {opacity: {to: 1.0}}, 1,

  YAHOO.util.Dom.setStyle(flickr, 'opacity', 0.0);
  YAHOO.util.Dom.setStyle(flickr, 'background', 'none');

  flickr.innerHTML = fakeflickr.innerHTML;
  fakeflickr.innerHTML = '';


And we're done. Easier than you thought it'd be, wasn't it?