DIV CSS 佈局教程網

yepnope.js 使用詳解:按需載入資源的語法與實例
編輯:關於JavaScript     

yepnope 是一個體積極小的資源載入器,特色是能把「載入」與「執行」分離,並依條件決定要載哪一份腳本。以下依序說明語法、優缺點與各類實例。

典型實例

yepnope({
    test : Modernizr.geolocation,
    yep  : 'normal.js',
    nope : ['polyfill.js', 'wrapper.js']
});

意義:若 Modernizr.geolocation 為真,載入 normal.js;為假則載入 polyfill.js 與 wrapper.js。

完整語法

yepnope([
    {
        test:     /* boolean(ish) 輸入條件 */,
        yep:      /* array (of strings) | string - 條件為真時載入的資源 */,
        nope:     /* array (of strings) | string - 條件為假時載入的資源 */,
        both:     /* array (of strings) | string - 條件真假皆載入 */,
        load:     /* array (of strings) | string - 條件真假皆載入 */,
        callback: /* function (testResult, key) | object { key: fn } 回調函式 */,
        complete: /* function 載入完成後執行的函式 */
    },
    ...
]);

為什麼選用 yepnope

  • Gzip 後僅 1.6K,比多數資源載入器都小。
  • 可同時載入 CSS 與 JS。
  • 作者宣稱已通過他能找到的所有瀏覽器測試。
  • 完全分離資源載入與執行,你能控制執行順序。
  • API 友善,便於資源的邏輯組合。
  • 模組化設計,可自行擴充(見稍後的 Prefixes 與 filters)。
  • 鼓勵按需載入。
  • 已整合進 Modernizr。
  • 預設依資源列表順序執行。
  • 可處理資源回退(fallback),且仍優先並行下載相依腳本。

看程式碼更好懂:

yepnope([
    {
        load: 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
        complete: function () {
            if (!window.jQuery) {
                yepnope('local/jquery.min.js');   // CDN 失敗就退回本機檔
            }
        }
    },
    {
        load: 'jquery.plugin.js',
        complete: function () {
            jQuery(function () {
                jQuery('div').plugin();
            });
        }
    }
]);

其他載入器可能得寫成這樣:

someLoader('https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js', function () {
    if (!window.jQuery) {
        someLoader('local/jquery.min.js', 'jquery.plugin.js');
        // 注意這裡與 yepnope 的差異:yepnope 載入失敗後只需重新載入備用資源,
        // 不會影響依賴該資源的其他檔案執行
    } else {
        someLoader('jquery.plugin.js');
    }
});

yepnope 的不足

  • 並不總是最快的。經最佳化後,labjs 等載入器可能優於 yepnope,仍需依實際情況挑選。
  • 需要為資源設定適當的 cache 標頭(這點很重要)。
  • 不像 RequireJS 這類函式庫有自己的建置工具與豐富 API,yepnope 只實作了基本的載入器功能。
  • 預設依你提供的資源列表順序執行,這有可能影響速度。

基本用法

直接傳入字串:

yepnope('/url/to/your/script.js');

傳入物件:

yepnope({ load: '/url/to/your/script.js' });

回調函式實例

(callback 中 url 為載入的資源檔名、result 為 test 參數的結果、key 為使用 key mapping 時的縮寫名)

yepnope({
    test: window.JSON,
    load: '/url/to/your/script.js',
    callback: function (url, result, key) {
        // 執行到這裡時,該腳本剛執行完
        alert('script.js has loaded!');
    }
});

complete 函式實例

yepnope({
    test: window.JSON,
    nope: 'json2.js',
    complete: function () {
        var data = window.JSON.parse('{ "json": "string" }');
    }
});

Key mapping 實例

yepnope({
    test: Modernizr.geolocation,
    yep:  { 'rstyles': 'regular-styles.css' },
    nope: { 'mstyles': 'modified-styles.css',
            'geopoly': 'geolocation-polyfill.js' },
    callback: function (url, result, key) {
        if (key === 'geopoly') {
            alert('This is the geolocation polyfill!');
        }
    }
});

回調函式也可以寫成物件形式,為每個 key 分別指定:

yepnope({
    test: Modernizr.geolocation,
    yep:  { 'rstyles': 'regular-styles.css' },
    nope: { 'mstyles': 'modified-styles.css',
            'geopoly': 'geolocation-polyfill.js' },
    callback: {
        'rstyles': function (url, result, key) {
            alert('This is the regular styles!');
        },
        'mstyles': function (url, result, key) {
            alert('This is the modified styles!');
        },
        'geopoly': function (url, result, key) {
            alert('This is the geolocation polyfill!');
        }
    },
    complete: function () {
        alert('Everything has loaded in this test object!');
    }
});

官方提供的三個 Prefixes

css! Prefix:可把任何副檔名的檔案當 CSS 載入。

yepnope('css!mystyles.php?version=1532');

preload! Prefix:預先載入資源到快取但不執行(下次 load 時才執行)。

yepnope({
    load: 'preload!jquery.1.5.0.js',
    callback: function (url, result, key) {
        window.jQuery;                 // undefined
        yepnope('jquery.1.5.0.js');
        window.jQuery;                 // object
    }
});

ie! Prefix(es):判斷是否為 IE 瀏覽器。除 ie! 外還支援 ie5、ie6、ie7、ie8、ie9、iegt5~iegt8、ielt7~ielt9 等寫法。

yepnope({
    load: ['normal.js', 'ie6!ie7!ie-patch.js']   // 僅 ie6 或 ie7 載入 patch
});

今日視角補充:yepnope.js 已停止維護,其作用已被 ES Module 的原生 import() 動態匯入、以及 <link rel="preload">/<script type="module"> 等標準機制取代,新專案建議採用標準方案。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved