jump to navigation

Best way to speed up Javascript (specifically jQuery) load times November 12, 2012

Posted by willhlaw in Javascript, jQuery, Web 2.0.
Tags: , , ,
trackback

Image

The obvious way is to use a popular CDN, short for Content Delivery Network, such as Google’s. Dave Ward explains the reasons very well in his article, “3 reasons why you should let Google host jQuery for you” and his three main points are:

  1. Decreased Latency – CDN allows the download to occur from the closest server to the user.
  2. Increased Parallelism – The local web server can be serving up content while the other connection is pulling from Google.
  3. Better Caching – Since so many other sites are using Google’s CDN, the user may already have the jQuery or javascript file in their cache.

However, there is a caveat. What if the connection to Google goes down? Can your site survive without jQuery? It should, if you developed the site with a responsive design and progressive enhancement.

The answer is to fall back to a local copy (code sample below).

  1. Write a script tag that refers to Google’s CDN.
  2. Then in the next script fragment, check to see if the jQuery or some public variable from the javascript file exists.
  3. If the object does not exist, then dynamically write another script to the page that refers to the local file.
<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if necessary -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.5.1.min.js">\x3C/script>')</script>

I learned this concise technique while watching a Twitter Bootstrap 101 tutorial (kudos to David Cochran for the great videos) that referred to this best practice that appears to have come from the HTML5 Boiler Plate project.

By the way, the numbers (from Pingdom) support Google as being most likely the best CDN to use.

CDN performance numbers


					
Advertisements

Comments»

1. Mohammed Safeer - November 12, 2012

Reblogged this on TechLog and commented:
Add your thoughts here… (optional)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: