隨着jQuery的版本更新,體積也愈來愈大,若是把jQuery放在本身的服務器上,會消耗很多的流量。而谷歌和百度等互聯網公司爲了方便開發者,提供了CDN加速服務,其中就包括jQuery。使用這些服務,不只能夠減輕本身的服務器的流量壓力,也能夠加快頁面加載速度,一箭雙鵰。
爲了防止出現某一個CDN服務器故障,特地寫了一個函數,函數會自動根據目標連接是否有效來自動加載jQuery文件。代碼以下: javascript
PHP版本: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; } } } ?>
Java Html版本html
<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>