Pick a Side
I noticed this code1 in a site today, and while clever, I don’t like it.
<!-- Add your site or application content here -->
<p>Hello world! This is HTML5 Boilerplate.</p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.0.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
The lines I’m focusing on are the first two <script> tags. The first loads jQuery from Google’s CDN. The second loads it from the current server if Google fails.
At first glance, this might look ok. You guarantee that jQuery is loaded2 before you move on, but you’ve also slowed down your page and most of the time, speed wins.
First of all, you create a blocking script situation. The page can’t keep loading3 until you load jQuery; if Google times out or fails, you’ve probably already waited a while. The reason you’d use Google’s CDN is mainly for speed4. If you’re worried about reliability, you just shouldn’t use it.
If you’re truly worried about speed, a much better option is to concatenate your scripts together. Ruby on Rails or a nice CMS like Harmony do this for you automatically, but you can always concatenate (and minify!) them yourself. Now instead of making 3 connections to fetch JavaScript files, you’ve only made one.
In general, I’ve started moving away from using Google’s versions, because the added speed is usually eclipsed by better concatenation.
Either way, this kind of clever code doesn’t get you anywhere. Pick a side.
1 This code is a standard part of HTML5 Boilerplate.
2 If you’ve ever been on a plane and tried to edit a site that uses Google’s CDN jQuery, you know the pain.
3 Some browsers may pre-fetch scripts later in the DOM, but don’t count on it.
4 There are other benefits, mainly “cross-site caching” but weigh all the alternatives.

2 Comments
Zach Dennis September 27, 2012 http://www.continuousthinking.com
Daniel, your fly-out picture on this post goes perfect with the title of this post.
Daniel Morrison September 27, 2012 http://collectiveidea.com/
Any inference of political leanings is merely a side effect of the design.
Post a Comment