Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
Web Dev + WordPress + Security

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

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 script 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 © <?php echo date('Y'); ?> Perishable Press</h6>
			</div>
		</div>

		<script src="https://perishablepress.com/press/wp-includes/js/perishable.js" type="text/javascript"></script>
		<script src="https://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 © <?php echo date('Y'); ?> Perishable Press • <a href="#top" title="Return to top of page">Up</a></h6>
			</div>
		</div>

		<div class="hide">
			<script src="https://perishablepress.com/press/wp-includes/js/perishable.js" type="text/javascript"></script>
			<script src="https://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="https://perishablepress.com/press/wp-includes/js/perishable.js" type="text/javascript"></script>
<script class="hide" src="https://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 ;)

About the Author
Jeff Starr = Web Developer. Book Author. Secretly Important.
Blackhole Pro: Trap bad bots in a virtual black hole.

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

  1. 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).

  2. 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).

  3. Perishable 2007/11/13 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.

  4. 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)

    Update: (404 link removed 2014/12/01)

  5. Perishable 2007/11/14 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).

  6. 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 :-)

  7. 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.

  8. Perishable 2007/11/18 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 ;)

  9. Jordan Gray 2008/03/04 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.)

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

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

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
BBQ Pro: The fastest firewall to protect your WordPress.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.