Prevent JavaScript Elements from Breaking Page Layout when Following Yahoo Performance Tip #6: Place Scripts at the Bottom

Published Monday, November 12, 2007 @ 11:56 pm • 11 Responses

By now, everyone is familiar with the Yahoo Developer Network’s 14 “best-practices” for speeding up your website. Certainly, many (if not all) of these performance optimization tips are ideal for high-traffic sites such as Yahoo or Google, but not all of them are recommended for smaller sites such as Perishable Press. Nonetheless, throughout the current site renovation project, I have attempted to implement as many of these practices as possible. At the time of this writing, I somehow have managed to score an average 77% (whoopee!) via the YSlow extension for Firebug.

Of the handful of these tips that I am able (or willing) to follow, number 6 — move scripts to the bottom — is definitely one of the easiest. The reason for doing this is at least twofold:

[…] it’s better to move scripts from the top to as low in the page as possible. One reason is to enable progressive rendering, but another is to achieve greater download parallelization.
— Yahoo! Developer Network

Many people mistakenly assume that the <script> element (and associated contents) must be located squarely in the document <head>, however, this simply isn’t true. As outlined in the official HTML 4.01 Document Type Definition and also in the official XHTML 1.1 Document Type Definition, the <script> element is allowed:

  • anywhere within the body element
  • within any block-level element
  • within any inline element
  • within the head element
  • virtually anywhere

Thus, the YDN advice of placing <script> elements at the bottom of the page is 100% standards-compliant. Indeed, after relocating my scripts to the bottom of the document body, my pages continue to validate with flying colors. I can’t honestly say that I have noticed any significant improvements in speed (e.g., page loading time, rendering time, etc.), but I do understand the logic behind this particular performance tip and will continue with its implementation, which, unfortunately, is not always 100% hassle-free..

Preventing script elements from breaking page layout

When script elements are placed in the document head, page layout is not effected in any browser. You can put a hundred of ‘em up there without affecting the visual presentation of underlying (X)HTML and/or CSS. Move any number of script elements to the bottom of the body element, however, and the page may render incorrectly in several popular browsers.

Apparently, Internet Explorer 7 and Opera 9 incorrectly attribute a literal height to script tags located outside of the head. In other words, rather than ignoring the scripts tags, these browsers are applying some sort of height property to each of them, thereby altering the intended layout of neighboring regions of the page. — Not good.

After relocating my scripts here at Perishable Press as follows:

			.
			.
			.
			<div id="footer">
				<h6>All Contents Copyright &copy; <?php echo date('Y'); ?> Perishable Press</h6>
			</div>
		</div>

		<script src="http://perishablepress.com/press/wp-includes/js/perishable.js" type="text/javascript"></script>
		<script src="http://perishablepress.com/mint/?js" type="text/javascript"></script>
		<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>
		<script type="text/javascript">
			_uacct = "UA-123456-1";
			urchinTracker();
		</script>
	</body>
</html>

..I noticed that my footer was no longer appearing as tightly as usual in Internet Explorer 7 or Opera 9.2:

[ Screenshot: broken footer positioning in IE 7 ]

[ Screenshot: broken footer positioning in Opera 9.2 ]

Here is how the footer should appear in a perfect world, where everybody uses the latest version of Firefox:

[ Screenshot: proper footer positioning in Firefox 2.0 ]

Fortunately, the solution to this (admittedly minor) presentational dilemma is rather simple: hide the script elements via CSS. Using a combination of display:none; and visibility:hidden; declarations applied to a container <div>, we may easily and swiftly restore our desired page layout. Using the following CSS:

.hide { display: none; visibility: hidden; }

..with a script-enclosing <div> container as follows:

			.
			.
			.
			<div id="footer">
				<h6>All Contents Copyright &copy; <?php echo date('Y'); ?> Perishable Press &bull; <a href="#top" title="Return to top of page">Up</a></h6>
			</div>
		</div>

		<div class="hide">
			<script src="http://perishablepress.com/press/wp-includes/js/perishable.js" type="text/javascript"></script>
			<script src="http://perishablepress.com/mint/?js" type="text/javascript"></script>
			<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>
			<script type="text/javascript">
				_uacct = "UA-123456-1";
				urchinTracker();
			</script>
		</div>
	</body>
</html>

..results in a completely hidden set of “optimally placed” script elements. Both IE 7 and Opera 9.2 (and therefore, I assume, virtually all major, modern browsers) will cease to apply dimensional properties to this “hidden” set of scripts. The bad news is that we must use additional, non-semantic markup in order to hide the scripts — CSS properties (i.e., display:none;) applied directly via class attributes will not work. For example, something like this proves entirely ineffective:

<script class="hide" src="http://perishablepress.com/press/wp-includes/js/perishable.js" type="text/javascript"></script>
<script class="hide" src="http://perishablepress.com/mint/?js" type="text/javascript"></script>
<script class="hide" src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>
<script class="hide" type="text/javascript">
	_uacct = "UA-123456-1";
	urchinTracker();
</script>

The good news, however, is that wrapping the <script> elements in a non-displayed, hidden <div> does not interfere with the functionality of the JavaScript enclosed therein. This had to be the case, of course, or I never would have spent my evening writing this article ;)

And finally, for those of you who are curious, here is what my current footer looks like in Internet Explorer and Opera now that I have employed the simple technique described above:

[ Screenshot: restored footer positioning in IE 7 ]

[ Screenshot: restored footer positioning in Opera 9.2 ]

And, of course, Firefox remains solid, displaying the original page layout precisely as intended:

[ Screenshot: proper footer positioning in Firefox 2.0 ]

That’s all for now — thanks for reading ;)


Dialogue

11 Responses Jump to comment form

1Louis

November 13, 2007 at 3:41 am

That was some pretty interesting work, thanks.

In my experience, putting the Js at the bottom showed a real difference in terms of loading times.

I guess it’s a matter of weight of the Js (and when you have animations in particular).

2Louis

November 13, 2007 at 6:36 am

Wow, i score 95 at the Yslow thing ! I just miss the #2 point which is adressed to professional websites.

Your post has made me go back into optimisation, and I’ve come to some new solutions that allow the compression and caching of my content (on a mutualised server, without zlib, and with very few possibilities for the user).

3Perishable

November 13, 2007 at 9:51 am

Thanks for the feedback, Louis. I am glad that you found the article interesting. The whole site overhaul thing is really quite educational, actually. It is amazing how many things need improving around here (on both sides of the server), especially when it comes to optimization and performance issues. Interesting that you mention caching and compression — they are some of the things I plan on digging into next.

4Louis

November 13, 2007 at 12:23 pm

Well, if you need help, I think I’ve come to something really effective.

Try to load a page of my weblog for example. It should be quit fast. Then try to reload it…

(use FireBug for more objectivity)

5Perishable

November 14, 2007 at 6:21 pm

I see what you mean! What’s your secret? I am interested in the methods described in your previous comment (about compression and caching). Also, what method are you using for adding e-tags and expires headers? (excellent site, btw).

6Louis

November 17, 2007 at 2:53 pm

I’ll write about it on my weblog, so you may read it there somewhen soon.

I’m affraid it will be in french, but the main idea will be understandable I guess (and services like Reverso do a good job translating fr —> eng).

Anyway, if you need more information then, you can just mail me :-)

7Louis

November 18, 2007 at 9:02 am

I don’t have the courage to translate all that into english, so here is the Google english version of my article

I find it pretty nice.

8Perishable

November 18, 2007 at 9:14 am

Great, thank you! I have saved a translated copy and will absorb the information before I dig into my site optimization project. Thanks again ;)

9Jordan Gray

March 4, 2008 at 9:05 am

I’ve never noticed this before — thanks for the heads-up!

Another small advantage of putting scripts at the end is that, since the DOM is mostly loaded at this point, you can start manipulating it immediately, thus eliminating the need for “onload” events can be delayed while waiting for images etc. to load. (This was a problem on a website I was working on.)

10Perishable

March 4, 2008 at 12:00 pm

Excellent points, Jordan — thanks for sharing with us! :)

11tim razo

April 16, 2008 at 10:55 pm

yeah, definitely would not have thought of that. great info!

Subscribe to comments on this post


[ Comments are closed for this post. ]

If you have additional information, contact me.

Contact Perishable Press

  • Contact Jeff via form

Search Perishable Press

About Perishable Press

Perishable Press is the virtual playground of Jeff Starr — visionary, founder and lead developer of Monzilla Media, a small web and graphic design company in the lush desert oasis of Moses Lake, Washington. Perishable Press features articles and tutorials on many aspects of digital design..

Read more..

Perishable on Twitter

automation is great: i've got photoshop batch processing 300+ images while FTP is simultaneously uploading them to the server..

Perishable on Tumblr

Tons of Firewalls

Tuesday, 7 October 2008, 1:45 am

Recently overheard on conservative talk radio (instructing listeners how to obtain a free promotional video from their new website):

“This website has tons and tons of firewalls, so you have to use your real email address to download the video..”

The Quiet Search Revolution

Monday, 6 October 2008, 12:15 pm

Just a thought.. As awesome as Google is these days, it would suck if they ended up owning the entire search-engine business. When they get to the point where all competition is impossible (due to their sheer size, financial resources, media influence, etc.), how many alternate search engines will have the resources for continuous improvement and top-quality search results? When this happens, we will have no choice but to do exactly what Google tells us to do.

As deeply ingrained as it is for everyone to instinctively and unthinkingly turn to Google for their search activity, it is time to leave a few alternate search tabs open for as much use as possible. Instead of using Google just because that’s what you always do, try your search on MSN, Yahoo, Ask, or any of the other independent search engines instead. Sharing traffic with other search engines is a nice, quiet way to keep the competitive spirit alive and well in the search-engine business.

Disappearing WordPress Posts

Wednesday, 1 October 2008, 7:50 pm

Today I experienced difficulties while trying to publish or even save new posts in WordPress. I would compose the post as usual, add all of the keywords, tags, meta tags, and so on, but as soon as I clicked the “Publish” or “Save” button, the post would just disappear from existence.

The weird thing is that during the drafting process, WordPress’ default auto-save feature showed that the post had been saved at expected intervals. Unfortunately, after trying to publish several different posts, WordPress showed absolutely no record of the posts ever being created. They simply vanished into thin air.

Fortunately, a little investigation revealed the culprit. If you should find yourself dealing with this same issue, here are some different things that you should try. First, re-upload fresh copies of your entire WordPress installation. I don’t know why exactly, but apparently various files can either go stale or completely disappear from the server. Overwriting or writing fresh files may do the trick.

If that doesn’t work, check your WordPress database for errors. In my case, a little investigation revealed that something had caused a couple of fatal errors in the wp_posts table. Fortunately, checking and repairing the table solved the issue.

Tumblr Battles

Wednesday, 1 October 2008, 5:30 pm

Please excuse the duplicate Tumbr posts.. seems there is no way to ping Tumblr to refresh/rebuild the RSS feed according to changes in post content. So, to resolve the issue I have discussed now like two or three times regarding paragraph elements and proper feed formatting, I have no choice but to repost a majority of my text posts.

This is necessary for the proper import and display of my Tumblr feed into WordPress. Currently, there are five items displayed at once, each styled according to proper inclusion of paragraph tags. Thus, whenever the Tumblr feed “forgets” to enclose single-paragraph posts with the proper tags, the result is an unstyled post entry displayed on my site.

Assuming that makes sense, you will please excuse my dust while I repost a few older entries in an attempt to reconstruct (the hard way) a properly formatted Tumblr feed.

More Optimization Measures

Wednesday, 1 October 2008, 5:27 pm

Another important step in improving the performance of my recent redesign involves the optimization of both CSS and JavaScript content. During development there were around 15 server requests for these two types of files, 10 JavaScript files and 5 CSS files. This was okay for my own use, but would not work for production purposes.

Optimizing these file types involves consolidation, compression, and caching. Consolidation of 10 JavaScript files into three is huge improvement. Now I deliver one JS file for the functionality of the site, one for Mint, and another for Analytics. Likewise for the stylesheets; after consolidation, a single stylesheet is delivered to all modern browsers. There are two additional stylesheets as well, but they are targeted at IE6 and mobile browsers and will not load elsewhere.

Once the files were consolidated as much as possible, it was time to optimize or “crunch” them. Using the sexy Flumpcakes CSS optimizer, I was able to reduce my stylesheets by around 25%. Likewise for JavaScript, I used xtreeme.com’s optimizer to shave an additional 20% off the size of my JS content.

Finally, once I had consolidated and compressed my JS and CSS files as much as possible, I wanted to further my optimization efforts by ensuring that these files were cached by the browser. By setting far-future Expires headers for everything but the statistical files, my site gains an additional performance boost by eliminating the need to reload preexisting content.

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • Adam Singer: Thanks for this. You're right, if it isn't broken, don't fix it. I was about to update my permalinks and install a plugin to redire...
  • Marilyn: It looks great on my browser! I wish I had that much creativity in my head! It's gorgeous!...
  • Randy: "Too girly?" It looks like a great design. Define "too girly!"...
  • Christopher Ross: .htaccess based redirects are wonderful. I'm always baffled by web professionals who don't take the time to learn more about them....
  • federico: Hi Jeff... tnx so much...it worked perfectly... c u Federico...
  • Cooltad: The skin seems (mostly) fine in my expert opinion. Your one of the few people able to make a design with a transparent table and a b...
  • Neal: The free Intro to Linux book is a great place to start http://www.ischool.utexas.edu/mirrors/LDP/LDP/intro-linux/html/index.html ...
  • Louis: @Jeff: Your “Archives” page is slick, although I would expect a cleaner implementation from such a vehement advoc...
  • Jeremy: Well I think that you may be over-critical, I don't see a darn thing wrong with it - I like it a lot!...
  • Jeff Starr: Alright, this is exactly the kind of information I was hoping to get. Lots of great ideas and recommendations here. I will be reading...

Read more recent comments..