3

同じページで2つのバージョンのjQueryを実行する必要がある状況があります(基本的に、1.4.2を実行しているWebサイトがあり、1.8.2を必要とするスクリプトを実行するブックマークレットがあります。これは良い考えではありません。しかし、私は今のところそれで立ち往生しています)。

既存のバージョンは1.4.2で、必要な新しいバージョンは1.8.2です。

私はrequire.jsを使用していて、この質問の投稿をここで見ましたが、何が最善の方法であるかを完全には理解していません。

私の場合、モジュールmain.jsがあります。

(function () {
var root = this;

require.config({
    baseUrl: "http://localhost:9185/scripts/app/"      
});

define3rdPartyModules();
loadPluginsAndBoot();

function define3rdPartyModules() {
    define('jquery', [], function () { return root.jQuery.noConflict(true); });              
    define('ko', [], function () { return root.ko; });       
}

function loadPluginsAndBoot() {      
    requirejs([], boot);
}

function boot() {        
    require(['bootStrapper'], function (bs) { bs.run(); });
}
})();

次に、これに似た他のいくつかのモジュール:

define('bootStrapper', ['jquery', 'presenter', 'repository', 'dataPrimer'],
function ($, presenter, repository, dataPrimer) {
    //some stuff here

私はrequirejsを初めて使用し、次のようにバージョン1.4.2を使用してmain.jsをロードする前にロードしています。

 $.getScript("http://localhost:9185/bundles/jsextlibs?v=GOyDBs-sBDxGR5AV4_K-m-   OK9DoE0LGrun5FMPyCO9M1", function () {     
    $.getScript("http://localhost:9185/Scripts/lib/require.js", function () {        
        $.getScript("http://localhost:9185/bundles/jsapplibs?v=9TJUN0_624zWYZKwRjap4691P170My5FUUmi8_fzagM1");
        $.getScript("http://localhost:9185/Scripts/main.js");
    });
});

誰かが私のコードを変更して、すべてのモジュールが1.4.2ですでに実行されているコードに干渉することなくバージョン1.8.2を使用できるようにする方法を教えてもらえますか?

ありがとう

デイビー

4

2 に答える 2

4
var reqOne = require.config({
context: "version1",
baseUrl: 'scripts/',
paths: {
    jquery: 'lib/jquery.min',
}
});

var reqTwo = require.config({
    context: "version2",
    baseUrl: 'scripts/',
    paths: {
        jquery: 'lib/jquery.modern',
    }
});

reqOne(["helper/util"], function(require,util) {
        //This function is called when scripts/helper/util.js is loaded.
            //If util.js calls define(), then this function is not fired until
                //util's dependencies have loaded, and the util argument will hold
                    //the module value for "helper/util".
//                    intheutil(); //This was done
                    console.log('util loaded');
});


reqOne(['require','jquery'],function(require,$){
    console.log( $().jquery );
});

reqOne(['require','jquery'],function(require,jq){
    console.log( jq().jquery );
});


reqOne(['require','jquery'],function(require,$){
    console.log( $().jquery);
});

reqTwo(['require','jquery'],function(require,$){
    console.log( $().jquery );
});

console.log('If no errors mean success!');

上記は、main.jsで使用したものです。完全な実装の詳細については、github の私の実装を参照してください。github.com

ここで、jquery.min は jquery バージョン 1.x であり、jquery.modern は jquery バージョン 2.x です。

console.log を使用しました。そのため、ブラウザ コンソールが有効になっている例を確認してください。上記の回答は、Require.js のドキュメントに基づいています。だから私はそれがあなたのケースの解決策でなければならないと思います。

ここに私の参照があります。 Require.js .

于 2015-01-28T13:05:42.023 に答える
1

Ajeeb KP と同様の方法を使用して解決できたほぼ同一の問題がありましたが、いくつかの重要な違いがあります。(Ajeeb のプロセスは実際には機能せず、jQuery CDN を使用すると一貫して失敗しました)。

基本的に、2 つの require.config インスタンスを作成し、それぞれのプロパティで異なるバージョンの jQuery を定義しました (特定の各インスタンスをマージした共通の require.config オブジェクトを使用して DRY を維持しました)。いずれかの require.config インスタンスが呼び出されると (つまり、RequireJS API が言うように「require に渡される」)、コールバック関数内のコードは、$ パラメーターとして jQuery.noConflict(true) を受け取る IIFE を実行します。IIFE 内で実行されるすべてのコード (require されたモジュールを含む) は、require に最初に渡された require.config インスタンスで定義されたバージョンの jQuery を実行します。

コードは次のとおりです。

/*
 * For merging each separate require.config object with a "common RequireJS config
 * properties" object. Meant to avoid e.g. baseUrl, common libs etc. between the 2 
 * (lodash cannot be used for this, as it's not yet loaded until all this completes)
 */ 
var mergeObjs = function mergeObjs(objIn1, objIn2) {
    var conglomerateObj = {};
    Object.keys(objIn1).forEach(function(item) {
        conglomerateObj[item] = objIn1[item];
    });

    return (function mergeIn(o1, o2) {
        Object.keys(o2).forEach(function(key) {
            if (typeof o1[key] === 'undefined') {
                o1[key] = o2[key];
            } else if (typeof o1[key] === 'object' && typeof o2[key] === 'object') {
                o1[key] = mergeIn(o1[key], o2[key]);
            }
        });
        return o1;
    }(conglomerateObj, objIn2));
};


// 'Common' RequireJS config properties object. Both config objects use these values.
var reqCommon = {
    baseUrl: '../scripts',
    paths: {
        lodash: '../public/lodash/lodash',
        bootstrap: '../public/bootstrap/js/bootstrap.min'
    }
};

// RequireJS config properties object 1. Configures section run with it to use an
// older version of jQuery (1.11.3) loaded using a CDN, for use with Bootstrap.
var req1 = require.config(mergeObjs({
    context: 'version1',
    paths: { jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min' }
}, reqCommon));

// RequireJS config properties object 2. Configures section run with it to use a 
// newer version of jQuery. Used for almost everything except Bootstrap.
var req2 = require.config(mergeObjs({
    context: 'version2',
    paths: { jquery: '../public/jquery' } //new, local version of jQuery
}, reqCommon));


//
// 1st require'd block; runs with req1 RequireJS properties object used & thus 
// jQuery 1.11.3. Mainly for running Bootstrap.
//
req1(['lodash', 'jquery'], function(main, ta, _) {

    // This IIFE is intended to load the older jQuery version in regardless of the presence of jQuery v2.1.4
    (function($) {
        console.log('1st block 1st section jQuery version: ' + $.fn.jquery); 
          //--> shows 1.11.3 as version
        window.jQuery = this.jQuery = $; // needed - Bootstrap uses jQuery on the window object.

        //Load Bootstrap after jQuery 1.11.3 confirmed loaded
        req1(['bootstrap'], function(bootstrap) {
            console.log("1st block 2nd section: bootstrap loaded!");
            console.log("1st block 2nd section: jQuery version: " + $.fn.jquery); 
          //--> still shows 1.11.3, even though block 2 has usually run by now
        });

    }(jQuery.noConflict(true)));
});


//
// 2nd require'd block; runs with req2 RequireJS properties object used & thus 
// jQuery 2.1.4. For almost everything except Bootstrap.
//
req2(['main', 'testaddedjsfile', 'lodash', 'jquery'], function(main, ta, _) {
    //this IIFE keeps the newer jQuery version separated from the old version.
    (function($) {
        console.log('2nd block jQuery version: ' + $.fn.jquery);
          //--> shows 2.1.4 as version
    }(jQuery.noConflict(true)));
    // the bind helps ensure calls to $ don't inadvertently call window.$. which will be occupy.
});

下部にある 1 番目と 2 番目の require されたブロックの IIFE は、この作業を行うために不可欠でした。

自分のファイルにオブジェクト (関数 mergeObjs) とデフォルト オブジェクトをマージする機能を追加する前は、require config オブジェクト (req1 と req2) が反復的で煩雑になりました。

Bootstrap は、概念を証明するために以下に含まれています。私が使用した特定の Bootstrap テンプレートでは、古いバージョンの jQuery がウィンドウ オブジェクトに存在する必要がありました...アプリ内の残りのコードは 2.1.4 を使用していました。

上記の設定により、Bootstrap と私自身のコードの両方を問題なく実行できました。各ブロックは一貫して適切なバージョンの jQuery を使用していましたが、1 つの注意点がありました。

長々と失礼しました - これは驚くほどトリッキーな問題でした。

于 2015-08-26T09:24:33.950 に答える