引入外部 CDN失效時--怎麼加載本地資源文件(本文以jquery爲例)

相信你們都使用過,百度或者CDN官網等提供的CDN靜態資源庫javascript

CDN官方靜態資源庫:https://cdnjs.com/html

七牛前端公開庫:http://staticfile.org前端

使用CDN能夠減小帶寬和http請求,也能夠減小一些服務器的壓力,java

從而提高頁面加載速度,也有利於提升用戶體驗。jquery

但有一個問題:假如你使用的是百度靜態資源庫。ajax

某天,忽然百度靜態資源庫崩了,那你網站引用的相應資源文件也會失效。api

這個時候應該怎麼辦呢?服務器

雖然這種狀況概率比較小,但爲了防範於未然,咱們仍是須要留一手。app

而後我就開始百度方法,真是五花八門,各類寫法都有,看的我是很矇蔽函數

有這種:

<script src="//ajax.google/jquery/1.9.2.js"></script>
<script>window.jQuery||document.write('<script src="jquery-1.9.2.js"></script>')</script>

有這種:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="jquery/jquery-1.7.2.min.js"%3E%3C/script%3E'))</script>

有這種:

<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.min.js "></script>
<script>
  //<![CDATA[
    if(typeof jQuery == 'undefined') {
       document.write(unescape("%3Cscript src='/Script/jquery-1.4.1.min.js' type='text/javascript' %3E%3C/script%3E"));
    } //]]>
</script>

不知爲什麼,總以爲以上寫法哪裏不對,但又說不出個因此然。
後通過一番尋找,終於找到了比較規範和正確的2種方法

方法一(推薦)

<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
 if (typeof jQuery == 'undefined') {
   document.write(unescape("%3Cscript src='/skin/mobile/js/jquery.min.js'%3E%3C/script%3E"));
 }
</script>

方法二

<script src="http://lib.sinaapp.com/js/jquery11/1.8/jquery.min.js"></script>
<script>window.jQuery || document.write(unescape("%3Cscript src='/skin/mobile/js/jquery.min.js'%3E%3C/script%3E"))</script>

:經本人實際測試,2種方法均可以。

而後這裏我又有一個疑問:不知道上面代碼中的 %3C 和 %3E是什麼意思?

後來先查了 unescape()這個函數, 接着又查了這個函數escape()

結果發現 %3C 和 %3E分別表示 '<' 和 '>',以下圖

原文參考:https://www.jianshu.com/p/950b5a16d935
https://www.jb51.net/article/140694.htm

相關文章
相關標籤/搜索