requirejsとjqueryを一緒に使用するにはどうすればよいですか?
質問
requirejsを使用したいのですが、jqueryを使用しています。最新のjQueryバージョンを使用していないため、requirejsとjqueryの合計バージョンを使用したくありません。 requirejsで仕事をするための最良の方法は何ですか?
解決
それも私の正確な質問です!また、古いjQueryだけでなく、より「伝統的な」JavaScriptライブラリも使用する必要があります。それをするのに最適なテクニックは何ですか? (あなたが気にしないなら、私はあなたの質問をより広くするためにあなたの質問を編集するかもしれません。)ここに私が学んだことがあります。
James Burkeが要求する著者は説明しました 結合されたrequirejs + jQueryファイルの利点. 。あなたは2つのことを手に入れます。
モジュール、
jquery
, 、利用可能で、それはjQueryオブジェクトです。これは安全です:// My module depends on jQuery but what if $ was overwritten? define(["jquery"], function($) { // $ is guaranteed to be jQuery now */ })
jQueryはすでに積み重ねられています
require()
またdefine()
もの。すべてのモジュールは、jQueryの準備ができていることが保証されています。あなたも必要ありませんrequire/order.js
jQueryは基本的に最初にロードするためにハードコーディングされていたため、プラグインがあります。
私にとって、#2はあまり役に立ちません。ほとんどの実際のアプリケーションにはあります たくさんの .js
それをファイル しなければならない 適切な順序でロード - サッドですが真。 SammyまたはUnderscore.jsが必要になるとすぐに、requirejs+jQueryファイルを組み合わせても役に立ちません。
私の解決策は、「Order」プラグインを使用して従来のスクリプトをロードする単純なRequireJSラッパーを書くことです。
例
私のアプリにこれらのコンポーネントがあると仮定します(依存関係によって)。
- 私のアプリ、 グレートアップ
- GreatAppはカスタムに依存します jquery (私が使用する必要がある古いバージョン)
- GreatAppは依存しています my_sammy (Sammyjsに加えて、私が使用する必要があるすべてのプラグイン)。これらは 整理されている必要があります
- my_sammyは依存しています jquery (sammyjsはjqueryプラグインです)
- my_sammyは依存しています Sammy.js
- my_sammyは依存しています sammy.json.js
- my_sammyは依存しています sammy.storage.js
- my_sammyは依存しています sammy.mustache.js
私の考えでは、上記のすべてが終わります .js
「従来の」スクリプトです。なしですべて .js
requirejsプラグインです。重要なのは:高レベルのもの(GreatApp、My_Sammy)であり、より深いレベルでは、従来のレベルに戻ります .js
ファイル。
ブート
それはすべて、Booterがexpectjsの開始方法を伝えることから始まります。
<html>
<head>
<script data-main="js/boot.js" src="js/require.js"></script>
</head>
</html>
の js/boot.js
設定とアプリケーションの開始方法のみを配置します。
require( // The "paths" maps module names to actual places to fetch the file.
// I made modules with simple names (jquery, sammy) that will do the hard work.
{ paths: { jquery: "require_jquery"
, sammy : "require_sammy"
}
}
// Next is the root module to run, which depends on everything else.
, [ "greatapp" ]
// Finally, start my app in whatever way it uses.
, function(greatapp) { greatapp.start(); }
);
メインアプリケーション
の greatapp.js
私は通常の見た目モジュールを持っています。
define(["jquery", "sammy"], function($, Sammy) {
// At this point, jQuery and SammyJS are loaded successfully.
// By depending on "jquery", the "require_jquery.js" file will run; same for sammy.
// Those require_* files also pass jQuery and Sammy to here, so no more globals!
var start = function() {
$(document).ready(function() {
$("body").html("Hello world!");
})
}
return {"start":start};
}
従来のファイルに関するJSモジュールラッパーを必要とします
require_jquery.js
:
define(["/custom/path/to/my/jquery.js?1.4.2"], function() {
// Raw jQuery does not return anything, so return it explicitly here.
return jQuery;
})
require_sammy.js
:
// These must be in order, so use the "order!" plugin.
define([ "order!jquery"
, "order!/path/to/custom/sammy/sammy-0.6.2-min.js"
, "order!/path/to/custom/sammy/plugins/sammy.json-0.6.2-min.js"
, "order!/path/to/custom/sammy/plugins/sammy.storage-0.6.2-min.js"
, "order!/path/to/custom/sammy/plugins/sammy.mustache-0.6.2-min.js"
]
, function($) {
// Raw sammy does not return anything, so return it explicitly here.
return $.sammy;
}
);
他のヒント
この質問は少なくとも2年前のものですが、これはまだrequirejs 2.0で問題であることに気付きました(require-jquery.jsはjquery 1.8.0を使用しますが、最新バージョンは1.8.2です)。
この質問が見られる場合は、 require-jquery.jsは、exlica.jsとjquery.jsだけでマッシュされました。 require-jquery.jsを編集して、jqueryパーツを新しいバージョンに置き換えることができます.
更新(2013年5月30日):これで、jssにパスとシムがあるため、jqueryとjqueryプラグインをインポートする新しい方法があり、古い方法はもはや必要ありません。 おすすめされた. 。現在の方法の要約バージョンは次のとおりです。
requirejs.config({
"paths": {
"jquery": "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min"
}
});
define(["jquery"], function($) {
$(function() {
});
});
見る http://requirejs.org/docs/jquery.html 詳細については。
最良のアプローチは、JQueryをRequireJSビルドの外に維持することです。
htmlにjquery.min.jsを含めるだけです。次に、このようなものでjquery.jsファイルを作成します...
define([], function() {
return window.$;
});
JasonsmithのAnwerは非常に役立つことがわかりました。
ただし、(tiny)Define Declaringモジュール( "require_jquery" "require_sammy")の個別のajax要求を避けるために、最適化する方法があります。 R.JSは最適化段階でそれを行うと思われますが、Path、Baseuriシステムと戦わないために事前にそれを行うことができます。
index.html:
<html>
<head>
<script data-main="js/loader.js" src="js/require.js"></script>
</head>
</html>
Loader.js:
// We are going to define( dependencies by hand, inline.
// There is one problem with that through (inferred from testing):
// Dependencies are starting to load (and execute) at the point of declaring the inline
// define, not at the point of require(
// So you may want to nest the inline-defines inside require(
// this is, in a way, short replacement for Order plug in, but allows you to use
// hand-rolled defines, which the Order plug in, apparently does not allow.
var jQueryAndShims = ['jquery']
if(window.JSON == null){
jQueryAndShims.push('json2')
define(
'json2'
, ['js/libs/json2.min.js']
, function() {
return window.JSON
}
)
}
// will start loading the second we define it.
define(
'jquery'
, ['js/libs/jquery_custom.min.js']
, function() {
// we just pick up global jQuery here.
// If you want more than one version of jQuery in dom, read a more complicated solution discussed in
// "Registering jQuery As An Async-compatible Module" chapter of
// http://addyosmani.com/writing-modular-js/
return window.jQuery
}
)
// all inline defines for resources that don't rely on other resources can go here.
// First level require(
// regardless of depends nesting in 'myapp' they will all start downloading
// at the point of define( and exec whenever they want,
// async in many browsers. Actually requiring it before the nested require makes
// sure jquery had *executed and added jQuery to window object* before
// all resolved depends (jquery plugins) start firing.
require(jQueryAndShims, function($) {
// will start loading the second we define it.
define(
'sammy_and_friends'
, ['jquery','js/libs/jquery_pluginone.min.js','js/libs/jquery_plugintwo.min.js','js/libs/sammy.min.js']
, function($) {
// note, all plugins are unaltered, as they are shipped by developers.
// in other words, they don't have define(.. inside.
// since they augment global $ (window.jQuery) anyway, and 'jquery' define above picks it up
// , we just keep on returning it.
// Sammy is attached to $ as $.sammy, so returning just Sammy makes little sense
return $
}
)
// second level require - insures that Sammy (and other jQuery plugins) - 'sammy_and_friends' - is
// loaded before we load Sammy plugins. I normally i would inline all sammy plugins i need
// (none, since i use none of them preferring jQuery's direct templating API
// and no other Sammy plug in is really of value. ) right into sammy.js file.
// But if you want to keep them separate:
require(['sammy_and_friends'], function() {
// will start loading the second we define it.
define(
'sammy_extended'
, ['sammy_and_friends','js/libs/sammy_pluginone.min.js','js/libs/sammy_plugintwo.min.js']
, function($) {
// as defined above, 'sammy_and_friends' actually returns (globall) jQuery obj to which
// Sammy is attached. So we continue to return $
return $
}
)
// will start loading the second we define it.
define(
'myapp'
, ['sammy_extended', 'js/myapplication_v20111231.js']
, function($, myapp_instantiator) {
// note, myapplication may, but does not have to contain RequireJS-compatible define
// that returns something. However, if it contains something like
// "$(document).ready(function() { ... " already it MAY fire before
// it's depends - 'sammy_extended' is fully loaded.
// Insdead i recommend that myapplication.js returns a generator
// (app-object-generating function pointer)
// that takes jQuery (with all loaded , applied plugins)
// The expectation is that before the below return is executed,
// all depends are loaded (in order of depends tree)
// You would init your app here like so:
return myapp_instantiator($)
// then "Run" the instance in require( as shown below
}
)
// Third level require - the one that actually starts our application and relies on
// dependency pyramid stat starts with jQuery + Shims, followed by jQuery plugins, Sammy,
// followed by Sammy's plugins all coming in under 'sammy_extended'
require(['jquery', 'myapp'], function($, myappinstance) {
$(document).ready(function() {myappinstance.Run()})
})
}) // end of Second-level require
}) // end of First-level require
最後に、myApplication.js:
// this define is a double-wrap.
// it returns application object instantiator that takes in jQuery (when it's available) and , then, that
// instance can be "ran" by pulling .Run() method on it.
define(function() {
// this function does only two things:
// 1. defines our application class
// 2. inits the class and returns it.
return function($) {
// 1. defining the class
var MyAppClass = function($) {
var me = this
this._sammy_application = $.sammy(function() {
this.raise_errors = true
this.debug = true
this.run_interval_every = 300
this.template_engine = null
this.element_selector = 'body'
// ..
})
this._sammy_application.route(...) // define your routes ets...
this.MyAppMethodA = function(blah){log(blah)} // extend your app with methods if you want
// ...
// this one is the one we will .Run from require( in loader.js
this.Run = function() {
me._sammy_application.run('#/')
}
}
// 2. returning class's instance
return new MyAppClass($) // notice that this is INITED app, but not started (by .Run)
// .Run will be pulled by calling code when appropriate
}
})
この構造(ゆるく置き換えます(重複?)はJSの注文プラグインを必要としますが、AJAXに必要なファイルの数をプルーズし、依存関係と依存ツリーの定義をさらに制御することができます。
また、jQueryを個別にロードすることに大きなボーナスがあります(通常は100kになります) - サーバーでのキャッシュを制御するか、jqueryをブラウザーのローカルストレージにキャッシュできます。こちらのAMD-Cacheプロジェクトをご覧ください https://github.com/jensarps/amd-cache 次に、define(「キャッシュ!」を含むステートメントを変更します。そして、それは(永遠に)ユーザーのブラウザに巻き込まれます。
define(
'jquery'
, ['cache!js/libs/jquery_old.min.js']
, function() {
// we just pick up global jQuery here.
// If you want more than one version of jQuery in dom, read a more complicated solution discussed in
// "Registering jQuery As An Async-compatible Module" chapter of
// http://addyosmani.com/writing-modular-js/
return window.jQuery
}
)
jquery 1.7.x+についての注意は、ウィンドウオブジェクトにそれ自体を取り付けないため、上記は変更されていないjquery 1.7.x+ファイルで動作しません。そこでは、jquery **をカスタマイズする必要があります。JSは、閉じる前にこれを含める必要があります "})(window);":
;window.jQuery=window.$=jQuery
コンソールに「jquery未定義」エラーがある場合、使用しているjqueryバージョンはウィンドウに付着していません。
コードライセンス:パブリックドメイン。
開示:上記のJavaScriptは、はるかに詳細な生産コードの言い換え(手操作)であるため、「擬似コード」の匂いがします。上記のコードは機能することが保証されておらず、提示されたように機能するようにテストされていません。監査、テストしてください。 js仕様に従って必要とされておらず、コードはそれらがなければコードが良くなるため、意図的に省略されています。
JHSの回答に加えて、 要求-Jquery githubページ readme.mdファイルから。組み合わせたjQuery/require.jsファイルを使用する最も簡単なアプローチと、個別のjquery.jsの使用方法の両方をカバーします。