Load jQuery with RequireJS
Load jQuery with RequireJS
我有一个问题加载jQuery与RequireJS。我只需要在我的应用程序中加载它一次,而不是在我编写的每个文件中加载它。我有以下项目:
my_project
|
|____ js
| |
| |____ jquery-1.7.2.min.js
| |
| |____ my_file.js
| |
| |____ my_file2.js
| |
| |____ my_file3.js
| |
| |____ jquery_loader.js
| |
| |____ loader.js
|
|____ index.html
我想加载jQuery只一次,并使用它在任何my_file*.js,不改变他们的代码。所以我写了一个jquery_loader.js,代码如下:
require.config ({
baseUrl: "/js",
paths: {
jquery: "jquery-1.7.2.min"
},
shim: {
"jquery": {
exports: "$"
}
}
});
requirejs (
[
"jquery"
],
function($){
console.log("jquery loaded");
}
);
然后我尝试将它加载到另一个文件中,像这样:
require.config ({
baseUrl: "/js",
paths: {
file: "my-file",
file2: "my-file2",
file3: "my-file3"
},
shim: {
"file": ["jquery_loader"],
"file2": ["jquery_loader"],
"file3": ["jquery_loader"],
}
});
requirejs (
[
"file",
"file2",
"file3"
],
function(file){
console.log("file loaded");
}
);
(my-file.js只包含一些jQuery的东西,像$("body").addClass("…");$ (" # id").append ("..."))
但是我得到以下错误:
ReferenceError: $ is not defined
我知道我没有以正确的方式加载jQuery,所以我希望能得到一些帮助。
提前感谢您
您可以使用以下方案:
require.config({
baseUrl: '/js_folder/',
paths: {
'jquery' : 'path/to/jquery'
}
})
那么你可以用
define([ "jquery" ], function($){
});
你可以把这一行放到requirejs配置文件中来加载jquery。
require(["jquery"]);
希望它会起作用。谢谢。
在调用jQuery函数之前,您应该等待它可用。
主要HTML内容;
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<script data-main="js/" src="js/require.js"></script>
</head>
<body>
<div id = "element" style = "background-color:red;position:relative;width:100px;height:100px;"></div>
<script>
require.config ({
baseUrl: "js/",
paths: {
file: "loader"
}
});
requirejs ( [ "file" ], function(file){
console.log("file loaded");
//Can use jQuery now
}
);
</script>
</body>
</html>
loader.js目录
require.config ({
baseUrl: "js/",
paths: {
jquery: "jquery-1.7.2.min"
}
});
define([ "jquery" ], function($){
});
正如我所料。确实有;
define([ "jquery" ], function($){
});
感谢Evgeniy。我已经更新了我的答案,以匹配这一点,使事情更清楚。
相关文章:
- Fighting with FRP
- issue with FB.Event.subscribe
- 以可优化的方式使用requirejs加载模板
- RequireJS向模块传递配置总是返回undefined
- geolocation-marker.js conflict with markerclusterer.js
- Angular 2.0 with JavaScript or TypeScript?
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- RequireJS with Angularjs 用于在同一页面上加载控制器
- 如何使用 jquery.validate with requirejs.
- Using moment.twitter.js with requirejs
- Backbonejs/Undercorejs with RequireJS-渲染后视图未重新加载Jquery
- RequireJS with jQuery Validation
- RequireJs with moment.js不会触发' init '
- Setting up jQuery noConflict with RequireJS
- Load jQuery with RequireJS
- Backbone AMD with requireJs
- Gruntfile issue with grunt-contrib-requirejs
- RequireJS with CommonJS modules
- Requirejs导出数组reset with [] literal不再被导出
- 在RequireJS中对define with dependencies感到困惑