One of the first questions that jQuery users need to ask is “should I host the core files on my own server, or rely on Google’s content delivery network (CDN) to host jQuery?”
While increased feature flexibility and control over source code integrity are cited as common reasons why hosting your own jQuery files makes sense, there are compelling reasons why letting Google handle the task makes sense — including the basic fact that no matter how good your hosting service is, it still likely pales in comparison to Google’s robust and exquisitely maintained CDN — and while bandwidth is much less expensive today than in the past, high volume sites could see significant savings by using these free host services, which perform as well and fast as (or better than) any premium offerings.
should I host the core files on my own server, or rely on Google’s content delivery network (CDN) to host jQuery?
Still, for some webmasters, the nagging feeling that all files should be self-hosted to ensure their contents and availability with the rest of the site’s files is hard to overcome.
For these users, we offer a way to have your cake and eat it too: relying on Google’s CDN to serve up the jQuery core, with a fallback to a selfhosted version “just in case.”
<?php
function loadjquery(){
$url = ?https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js?;
if(@fopen($url, ?r?)){echo ?<script type=\?text/javascript\? src=\?? . $url . ?\?></script>\n?;
} else {
echo ?<script type=\?text/javascript\? src=\?/js/jquery.js\?></script>\n?;
}
}
?>
Not only will this technique provide your website with a more efficient infrastructure while saving on bandwidth and other expenses, but it could dramatically speed up your site’s loading time, since visitors may already have downloaded the jQuery package from the Google CDN. Note that Microsoft and jQuery also provide CDN services, making for additional options, such as using the Google CDN as the primary source and Microsoft’s CDN as the fallback source — and then perhaps a tertiary fallback to a self-hosted copy.
However you choose to implement jQuery, combining free CDN delivery with a selfhosted backup copy will easily give you and your site’s users the best of both worlds.