Friday, March 14, 2025

Optimization Techniques that Do the Document Body Good

Optimization Techniques that Do the Document Body Good

Optimizing your web pages for different browsers, platforms, and devices has evolved to consume a sizeable chunk of one’s development efforts. To minimize its impact, some developers, most notably Paul Irish, have compiled many of the best practices for getting your documents to load as quickly and render as consistently as possible across the full spectrum of available devices into framework templates. In today’s article, we’ll be looking at optimizing techniques that specifically target the document body.

Consider Placing your Scripts at the Bottom of the Page

As sites rely more and more on JavaScript libraries – both proprietary and open source – loading times have become a concern in some cases. Traditionally, scripts are placed in the document HEAD. Then, any initializing code that references the document body is done in the window.onload event. While there is nothing wrong with that approach, there are some caveats that you should be aware of. The first is that the document markup won’t be parsed until the scripts have all been loaded, since the document is read and presented from top to bottom. This issue can be somewhat mitigated by running your scripts through a minifier so as to compress them, but that can only do so much as they mostly remove whitepace.

A secondary concern is that, as you add scripts, you have to be careful to not clobber other initializing code by adding event listeners to the onload event, rather than simply assign a handler directly to the event, as in:

window.addEventListener('onload', myHandler, false);

//as opposed to

wondow.onload = myHandler;

 

  <div id="container">
    <header>

    </header>
    <div id="main" role="main">

    </div>
    <footer>

    </footer>
  </div> <!--! end of content div -->
  <script src="js/libs/modernizr-2.0.6.min.js"></script>
  <script src="js/libs/jQuery.min.js"></script>
  <script src="js/libs/myScript.js"></script>
  <script src="js/libs/formValidation.js"></script>
  <script src="js/libs/fancyEffects.js"></script>
</body>
</html>

Use Hosted JS Framework Loading with Fallback

A lot of popular JavaScript libraries are hosted by Public repositories like Google. Using the hosted versions can give you faster loading speeds as well as better cross site caching. The downside is that you can’t work on your page without an active Internet connection. If you’re one of those people like me, who isn’t always connected, you’ll want to use your own script for development. The way to have both is to use a JavaScript OR operator to test for the hosted version of the script. That way, you can be ret assured that your local script will only be used as the fallback choice:

<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.6.2.min.js"><\/script>')</script>

Optimizing Google Analytics

Google Analytics is a very popular tool for tracking websites’ traffic, user behavior, and visits. Google’s asynchronous tracking snippet code has been revised several times already, but it can still use some more optimizations. Ideally, you should avoid setting the window._gaq via multiple calls to Array.push(). It’s better to simply set it to an array of arrays. The other important step is to serve up the Google analytics script using the same protocol as the document. This snippet uses Modernizr, but it could just as easily be done without it. Note that the omission of the document prefix (location.protocol instead of document.location.protocol) saves 9 bytes!

<!-- Change UA-XXXXX-X to be your site's ID -->
<script>
  window._gaq = [['_setAccount','UAXXXXXXXX1'],['_trackPageview'],['_trackPageLoadTime']];
  Modernizr.load({
    load: ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js'
  });
</script>

Give IE6 Users a Helping Hand

I now what you’re thinking: “who the heck still used IE6?!” Actually, more than anyone wants to admit. I know first hand, that lots of Canadian Federal Government departments are still using it (thankfully, I’m not ne of them!). Being somewhat outdated, now, IE 6 does This snippet prompts IE6 users to install Chrome Frame, a far better rendering engine:

<!--[if lt IE 7 ]>
  <script src="//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js"></script>
  <script>window.attachEvent('onload',function(){CFInstall.check({mode:'overlay'})})</script>
<![endif]-->

 

Some CSS Tips

That covers optimizations that should be included within the document <body></body> tags. Now lets’ move on to some CSS rules that will affect how document elements will display and behave.

Formatting Quoted Code

Ideally, text should wrap when it reaches the walls of its container, such as within <pre></pre> and <div></div> tags, while still preserving line breaks and whitespace across different browsers. Here’s a CSS rule that does that:

pre {
  padding: 15px;
  white-space: pre;      /* CSS2 */
  white-space: pre-wrap; /* CSS 2.1 */
  white-space: pre-line; /* CSS 3 (and 2.1 as well, actually) */
  word-wrap: break-word; /* IE */
}

Before:

pre_tag_text_before_css_wordwrap_rule_jpg

After:

pre_tag_text_after_css_wordwrap_rule.jpg

Aligning Labels

Aligning labels with their associated inputs such as checkboxes, radio buttons, and textboxes, can be difficult to achieve in some older browsers. Here’s a way to achieve consistency across browsers using CSS rules:

input[type="radio"]    { vertical-align: text-bottom; }
input[type="checkbox"] { vertical-align: bottom; *vertical-align: baseline; }
.ie6 input             { vertical-align: text-bottom; }

Before:

label_and_checkbox_alignment_before_css_rule.jpg

After:

label_and_checkbox_alignment_after_css_rule.jpg

The effect is subtle but it brings the label text up by a couple of pixels.

Clickable inputs

Sometimes, when you hover over a clickable input, the mouse pointer doesn’t change to the “pointer” cursor to let you know that this item is indeed clickable. The solution is to handle it ourselves by explicitly setting the mouse pointer via CSS:

/* hand cursor on clickable input elements */
label, input[type=button], input[type=submit], button { cursor: pointer; }

Before:

mouse_pointer_before_css_rule.jpg

After:

mouse_pointer_after_css_rule.jpg

Conclusion

A lot of work goes into making a page display consistently across browser makes and versions. However, the saying that “where there’s a will, there’s a way” is definitely applicable here. You just need to know the optimal way to achieve your goal. In most cases, there is a solution to be found.

Robert Gravelle
Robert Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured