jquery
  • requirejs
  • 2013-02-08 25 views 1 likes 
    1

    我的應用程序的結構是這樣的:RequireJs只有加載的JQuery當我配置的路徑選擇

    ... 
    javascripts/ 
        - main.js 
        lib/ 
         - jquery-1.9.0.min.js 
         - require.js 
    

    我有一個HTML頁面,如:

    <script type="text/javascript" data-main='/assets/javascripts/main' src='/assets/javascripts/lib/require.js'></script> 
    

    我main.js樣子:

    //main.js 
    require.config({ 
        paths: { 
        jquery: 'lib/jquery-1.9.0.min' }}); 
    
    require(['jquery'], function($) { 
        return $(function() { 
         return console.log('dom ready'); 
        }); 
    }); 
    

    這一切都正常,並且HTML頁面在控制檯中顯示'dom ready'。問題是,當我刪除的路徑的配置和嘗試加載jquery的是這樣的:

    //Updated main.js 
    require(['lib/jquery-1.9.0.min'], function($) { 
        return $(function() { 
         return console.log('dom ready'); 
        }); 
    }); 
    

    其中我已刪除的路徑配置,並試圖通過指定其路徑以加載jquery的。這給了我「未定義不是一個函數」引用$變量。奇怪的是,我仍然看到jquery-1.9.0.min通過require.js發起的網絡。這裏發生了什麼?這是一個錯誤?

    回答

    4

    不是一個錯誤。 jQuery將自己導出爲一個命名模塊。這意味着您必須將其作爲路徑配置選項。

    // Expose jQuery as an AMD module, but only for AMD loaders that 
    // understand the issues with loading multiple versions of jQuery 
    // in a page that all might call define(). The loader will indicate 
    // they have special allowances for multiple jQuery versions by 
    // specifying define.amd.jQuery = true. Register as a named module, 
    // since jQuery can be concatenated with other files that may use define, 
    // but not use a proper concatenation script that understands anonymous 
    // AMD modules. A named AMD is safest and most robust way to register. 
    // Lowercase jquery is used because AMD module names are derived from 
    // file names, and jQuery is normally delivered in a lowercase file name. 
    // Do this after creating the global so that if an AMD module wants to call 
    // noConflict to hide this version of jQuery, it will work. 
    if (typeof define === "function" && define.amd && define.amd.jQuery) { 
        define("jquery", [], function() { return jQuery; }); 
    } 
    

    https://github.com/jquery/jquery/blob/master/src/exports.js

    如果你不那麼庫將仍負荷(如您所見),但它不會正確地返回到你需要/定義回調

    +0

    非常有趣!謝謝一堆! – Mark

    0

    更改爲define而不是require

    define(['lib/jquery-1.9.0.min'], function($) { 
        return $(function() { 
         return console.log('dom ready'); 
        }); 
    }); 
    
    +1

    這將導致同樣的行爲。 – Mark

    相關問題