Haji
Haji

Reputation: 1775

Scripts Dependencies Using RequireJS Shim

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?

Upvotes: 3

Views: 1868

Answers (3)

xpy
xpy

Reputation: 5611

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.

Upvotes: 0

ekeren
ekeren

Reputation: 3458

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?

Upvotes: 1

Simon Smith
Simon Smith

Reputation: 8044

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.

Upvotes: 2

Related Questions