4

I have the following folder structure:

  • index.html
  • js/
    • libs/
      • require.js
      • jquery.js
    • main.js

In index.html I added the following line to the head section:

<script data-main="js/main" src="js/libs/require.js"></script>

When I add a simple alert to main.js, it works. When I want to use jQuery, it's not working:

require(['libs/jquery'], function ($) {
    $('#test').html('123');
});

In the chrome web inspector, I see that jquery loaded succesfully, but the text doesn't appear in my div. When I move jquery out of ./js/libs and just put it in ./js (and ofcourse change the dependency to ['jquery']), it works.

What am I doing wrong? Why can't I just put jquery in ./js/libs to keep things organized?

Thanks

1
  • Is it possible that the DOM is not ready when your main.js runs and hence #test isn't updated? Try wrapping your test code in $( function() { ... }); Commented Aug 5, 2012 at 17:31

2 Answers 2

8

If I configure a path

require.config({
    paths: {
        'jquery': 'libs/jquery'
    }
});

and change the require to:

require(['jquery'], function ($) {
    $('#test').html('123');
});

it appears to be working. If someone could explain me why.

Sign up to request clarification or add additional context in comments.

2 Comments

when jQuery calls define (the way AMD modules are defined/offered to any AMD loader) it gives itself the module-name jquery. Now if you call require(['lib/jquery'], ...) it will find jquery.js in lib, load the file and figure that there it is not named lib/jquery but only jquery. Therefore not the module you are looking for. At leasts that is how I understood this problem.
Its works even if you do not have the $ reference in the function call back because the jQuery refernce is in global scope. In order to avoid that you need to define jQuery as a module and resolve the name conflict and return it as an object. Something like define(["jQuery"], function(){ return jQuery.noConflict(true); });
0

You have to provide basePath in order it to work correctly. In your case it's just js. You can do it in the beginning on main.js file.

require.config({
    baseUrl: '/js'
});

after that this code will work, because it will concatenate baseUrl with your relative url.

require(['libs/jquery'], function ($) {
    $('#test').html('123');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.