jQuery使用CDN加速


使用新浪、百度、谷歌和微软的CDN加速jQuery

随着jQuery的版本更新,体积也越来越大,如果把jQuery放在自己的服务器上,会消耗不少的流量。而谷歌和百度等互联网公司为了方便开发者,提供了CDN加速服务,其中就包括jQuery。使用这些服务,不仅可以减轻自己的服务器的流量压力,也可以加快页面加载速度,一举两得。
为了防止出现某一个CDN服务器故障,特意写了一个函数,函数会自动根据目标链接是否有效来自动加载jQuery文件。代码如下:

PHP版本:


<script type="text/javascript" src="<?php jquery_url(); ?>'"></script>
 
<?php
 
function jquery_url(){
	$jquery = array(
		'http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js',
		'http://libs.baidu.com/jquery/1.7.2/jquery.min.js',
		'http://code.jquery.com/jquery-1.7.2.min.js',
		'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
		'http://ajax.microsoft.com/ajax/jquery/jquery-1.7.2.min.js'
	);
	foreach($jquery as $v){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $v);
		curl_setopt($ch, CURLOPT_NOBODY, true);
		curl_exec($ch);
		$code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
		curl_close($ch);
		if($code == 200){
			echo $v;
			break;
		}
	}
}

?>

JavaScript版本:

<html>
<head>
<meta charset="utf-8" />
<title>jQuery动态加载</title>
<script type="text/javascript">
// jQuery的CDN节点列表
var jquery_url = new Array();
jquery_url[1] = ‘http://libs.baidu.com/jquery/1.7.2/jquery.min.js’;
jquery_url[2] = ‘http://code.jquery.com/jquery-1.7.2.min.js’;
jquery_url[3] = ‘http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js’;
jquery_url[4] = ‘http://ajax.microsoft.com/ajax/jquery/jquery-1.7.2.min.js’;
// 加载jQuery失败触发Load函数
function Load(n){
// 删除加载失败的jQuery
var old = document.getElementById(‘load_jquery’);
old.parentNode.removeChild(old);
n += 1;
var jq_url = document.createElement(‘script’);
jq_url.setAttribute("type", "text/javascript");
jq_url.setAttribute("src", jquery_url[n]);
jq_url.setAttribute("id", "load_jquery");
// 加载下一个节点
jq_url.setAttribute("onerror", "Load("+n+")");
document.getElementsByTagName("head")[0].appendChild(jq_url);
}
// 显示当前节点
window.onload = function(){
document.getElementById(‘my’).innerHTML = "当前节点:" + document.getElementById(‘load_jquery’).src;
}
</script>
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js" id="load_jquery" onerror="Load(0)" ></script>
</head>
<body>
<div id="my"></div>
</body>
</html>


发表回复