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