I'm upgrading from jQuery 1.8 to 1.9 and since jQuery.browser() is removed, I will use jQuery Browser Plugin.
My requirejs config file (loaded using data-main="") looks somewhat like this:
(EDITED - added more code snippets)
main-comp.js
require.config({
paths: {
jquery: 'libs/jquery/jquery1.9.1.min',
utils: 'modules/utils',
myController: "controllers/myController",
browserPlugin: 'libs/jquery/jquery.browser.min'
},
shim: {
browserPlugin: {
deps: ['jquery']
}
}
});
require(['myController', 'jquery'], function (controller, $) {
$(controller.start);
}
);
moduls/utils.js
define(['browserPlugin'], function () {
return {
browser: $.browser
};
});
myController.js
define(['utils'], function (utils) {
function start() {
console.log(utils.browser.msie)
}
return {
start: start
};
});
Everything seemed to work properly, but then I saw that sometimes in IE only I get a 'jQuery' is undefined (it's a capital Q there) or '$' is undefined errors from the jquery.browser.min.js file.
I thought the deps means that jquery will load before the jquery.browser file but apparently this isn't always the case. I tried following this answer and add exports: "$.fn.browser" but with no success.
When running an optimized version (minify+uglify using r.js) I haven't encountered it.
What am I doing wrong?
You need to ensure you reference $ as a parameter in the require callback. Like so:
require(['myController', 'jquery'], function (controller, $) {
$(controller.start);
}
);
This ensures that jQuery is available to use. It is a bit of an odd one as it will expose itself globally anyway so it will sometimes work regardless, but the correct way is to explicitly require it and use it inside the callback as a parameter.
It looks like you are missing jquery dependency in moduls/utils.js, please try:
define(['jquery', 'browserPlugin'], function ($) {
return {
browser: $.browser
};
});
and also, just to be on the safe side, add jquery to your shim :
jquery: {
exports: "$"
},
By the way, why don't you use $.browser in your code and just load the jquery plugin using the shim configuration?
I had the same problem, the script in data-main is loading asynchronously, that means that it may load after the scripts it defines.
The solution is to load another script with the require.config right after the require.js script.
data-main Entry Point Documentation.
Related
I'm working on a JavaScript module that uses jQuery, some functions of jQuery UI (draggable) and jPlayer. Recently I made myself familiar with requireJS to manage the dependencies properly.
I don't want to produce conflicts with a possibly already existing jQuery version that the site that includes my script uses. For this reason I am mapping the jQuery dependencies to a module "jquery-private" with a call of noConflict(), as is described in the requireJS guide.
As jQuery UI takes up a lot of space, I would also like to just include the modules that I am actually using. ui.draggable has the dependencies ui.core, ui.mouse and ui.widget, so I should have to include these 4 modules.
My problem is that I would like the jQuery UI modules and the jPlayer module to use my own version of jQuery, but obviously it isn't accessible by the global $ variable after I called the noConflict() method. Unfortunately neither jQuery UI nor jPlayer are AMD modules, so I needed to make shim configurations for them.
Here is my definition of the dependencies:
require.config({
baseUrl: 'javascript/modules',
paths: {
jquery: 'jquery-2.1.3',
jPlayer: 'jquery.jplayer',
uiCore: 'jquery.ui.core',
uiMouse: 'jquery.ui.mouse',
uiWidget: 'jquery.ui.widget',
uiDraggable: 'jquery.ui.draggable'
},
map: {
// '*' means all modules will get 'jquery-private'
// for their 'jquery' dependency.
'*': { 'jquery': 'jquery-private' },
// 'jquery-private' wants the real jQuery module
// though. If this line was not here, there would
// be an unresolvable cyclic dependency.
'jquery-private': { 'jquery': 'jquery' }
},
shim: {
jPlayer: {
deps: ['jquery']
},
uiCore: {
deps: ['jquery']
},
uiMouse: {
deps: ['jquery','uiCore']
},
uiWidget: {
deps: ['jquery','uiCore']
},
uiDraggable: {
deps: ['jquery','uiCore','uiMouse','uiWidget']
}
}
});
require(["json","jquery","jPlayer","uiDraggable"], function(json,___jQuery,jplayer,uiDraggable) {
(...)
}
Obviously this code produces errors as the $ variable in the jQuery UI modules is not defined.
Is there any way to pass my own jQuery object to modules? The top answer in another thread (How use require.js to load jQuery with noConflict) suggests that what I am trying to do is not possible, but maybe there is some other way to do it?
If there is none, I probably have to use global variables and heavily edit the included modules, which kind of makes it questionnable why to use a dependency management library like requireJS in the first place...
I found the following code on top of each module in jquery.ui:
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {...});
And it means jquery.ui checks when global AMD "define" function is defined and uses 'jquery' as AMD reference for module.
It will use no conflict of jquery based on requirejs recommendation in this and this.
And about how to use jQuery with AMD.
I'm using backbone.js and require.js. I have a script with files dependencies but the problem is that a file is not loaded before executing my script. So, a function is not defined. Here is the code exemple :
define([
'jquery',
'jqueryUi',
'holder',
'knob',
'jquery.ui.widget',
'iframeTransport',
'fileupload',
'knobScript',
], function($, ui, Holder) {
$(document).ready(function() {
$('#upload').fileupload({...}); // This one is unedefined because the script from the file fileupload is not completely loaded
});
});
Is someone has a solution to be sure that the script fileuplaod called in define is fully loaded before executing the script with the function (functionFromFileupload) ?
Thank for your help
To complement Evgeniy's comment: The problem is not that fileupload is loaded after your function. It will be loaded before running your function, that is the contract of Require. (If you can confirm it doesn't, then it would probably be a misconfiguration or less probably a bug of Require.)
Most probably the problem is that, sometimes, fileupload may be loaded before jQuery. Thus, it does not find the jQuery object to plug to and $(...).fileupload(...) fails. Use shim in the Require configuration, e.g. as:
require.config({
...
shim: {
fileupload: {
deps: ["jquery"]
}
...
}
...
});
You will probably have to shim other things too, e.g. jQueryUI.
The line $("body").slimScroll(); throws error, because slimScroll is not defined. That is because require.js probably doesn't load automatically shim keys, if you are requiring any module, that is specified as dependency in shim (i think if i have shim jquery.slimscroll and its dependency is jquery, then when i require jquery, it automatically loads jquery.slimscroll - this behavior doesn't happen).
So the right way is call define(['jquery', 'jquery.slimscroll') function ($) ..., so require knows i need jquery.slimscroll and because it is in shim, it will be loaded a bit different, because it is not AMD compatible.
Problem is that if i have lot of jquery plugins, i need always pass all plugins that i need in define call. Is there any way, how to solve this type of annoying behavior and write just define(['jquery'], function ($) ..?
require.config({
baseUrl: 'js/bower',
paths: {
react: 'react/react-with-addons',
jquery: 'jquery/dist/jquery',
'jquery-private': '../jquery-private',
'jquery.slimscroll': 'jquery-slimscroll/jquery.slimscroll.min'
},
map: {
'*': {
jquery: 'jquery-private',
},
'jquery-private': {
jquery: 'jquery'
}
},
shim: {
'jquery.slimscroll': ['jquery']
}
});
require(['jquery'], function ($) {
$("body").slimScroll();
});
You could just add the jquery plugins to the dependencies of your jquery-private module.
define(['jquery', 'jquery.slimscroll', ...], function (jQuery) {
return jQuery.noConflict(true);
});
This way, when any module requires jquery, the plugins are also loaded at the same time.
I'm assuming that jquery-private is meant to load jQuery so that it does not conflict with other version of jQuery. That's what my example reflects above but it does not generally matter what the module actually does.
With this method you still need to have a shim configuration for each plugin that is not an AMD module. Moreover, your plugins will have to get a map setting just like for jquery-private to get the real jquery module. Otherwise, there will be a circular dependency.
I'm having a lot of troubles with RequireJS, I get errors simply by using a define module.
Let's assume I have this configuration:
require.config({
baseUrl: "js/",
paths: {
jquery: "libs/jquery/jquery-2.0.2.min",
handlebars: "libs/backbone/template/handlebars",
lodash: "libs/backbone/template/lodash.min",
backbone: "libs/backbone/backbone-1.0.0.min",
helper:"app/helper",
jquery_cookie:"libs/jquery/plugin/jquery.cookie",
text:"libs/require/text-2.0.7"
},
shim: {
"lodash": {
exports: '_'
},
"handlebars": {
deps:["jquery"],
exports: 'Handlebars'
},
"backbone": {
deps: ["helper", "lodash", "handlebars", "jquery"],
exports: "Backbone"
}
},
urlArgs: "bust=" + (new Date()).getTime()
});
define(["jquery"], function ($) {
console.log('define "jquery" on config.js');
return $;
});
console.log("end config.js");
First, I've tried the classic way, I've loaded a config file where I have all the dependances of my JavaScript files, I'm using jQuery, Backbone and other libs.
<script type="text/javascript" data-main="config" src="js/libs/require/require-2.1.6.min.js"></script>
<script type="text/javascript">
require(["jquery"], function ($) {
console.log("jquery loaded");
});
</script>
With this configuration, i get these errors and logs sequence:
Uncaught Error: Mismatched anonymous define() module: function (){return r}
> http://requirejs.org/docs/errors.html#mismatch
end config.js
define "jquery" on config.js
It seems the error is referred to the function require.config(...);
I thought it was a load problem, so I've tried to use the var require as described in RequireJS site without solving it.
The absurd thing is I'm working on a fullscreen app built in Backbone with the same configuration without getting any problem, here I need to work more with different views and I cannot start, basically the whole difference is here I'm using CakePHP.
Why this won't work, where I'm wrong?
The jQuery version you are using already has AMD support. So you don't have to use shim for it. You can directly give the path and start using it.
Since the module is already defined in the jQuery library, it throws errors when you try to redefine it. The following code tries to define an anonymous module.
define(["jquery"], function ($) {
console.log('define "jquery" on config.js');
return $;
});
remove the above code and should work fine. The following code uses require method to load the jquery module.
require(["jquery"], function ($) {
console.log($(document));
});
Hopefully this works.
require(['underscore'], function ($, _) {
...
});
Doesnt work! (_ is not a function)
How to manage it?
Note that underscore.js doesn't register itself as an AMD module (though it did for a brief time in earlier versions), thus it can't be used in a require() call without some configuration using "shim:" like so:
require.config({
paths: {
jquery: 'lib/jquery.min',
underscore: 'lib/underscore-min'
}
shim: {
"underscore": {
exports: "_"
}
}
});
See the docs at: http://requirejs.org/docs/api.html#config-shim
Before shim: was added to require.js, you could do something similar with the plugin use.js (in case you need to use an older version of require.js).
As of this writing, the current version of require.js is 2.1.8.
Alternatively, you can use lodash.js as a drop-in replacement for underscore.js - it does register itself as an AMD module, so you can use it with no extra config: http://lodash.com/
I think the problem is the order of args passed in to your callback.
Should be:
require(['underscore'], function (_, $) {
...
});
Also you need to be using underscore version 1.2.1 which added this functionality.
require(["underscore"], function() {
console.log(_ === window._);
});
it all depends where the script is based.
since i don't see you specified a baseUrl, the baseUrl will be the default,
that means, either 2 things:
your script is directly inside a html file, and in your case it
will thus look for underscore.js in the same directory of the html
file
your script is in a javascript file referenced by your html
file, it will now search for underscore.js in the directory of your
custom javascript file.
check if the underscore.js is actually there.
Here are the checkpoints for you to make sure what you need works
Get require-jquery.js and put it to your /js-root dir
Add to your HTML, right before the closing </body> tag: <script data-main="/js-root/main-js-file-name" src="/js-root/require-jquery.js"></script>
Get underscore adapted for AMD, and put it to /js-root dir as well
In main-js-file-name.js
write:
require(["jquery", "underscore"], function ($, _) {
...
});
Similarly, in your non-main AMD JS files, when defining a module, to use _, write:
define(["jquery", "underscore"], function ($, _) {
...
return theModuleObjectOrFunction;
});