1

Just for fun, I want to load jquery using require.js. So, I made the following:

amd.js

define(["jquery-3.3.1"], function($) {
    console.log(typeof $);              // reports undefined
    $("h1").html("Hello from AMD");     // causes TypeError (see below)
});

My HTML file is really simple and just has a blank <h1> element and the usual require.js definition.

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

Also, my root folder, where everything is, also contains the jquery-3.3.1.js source file.

You may see the whole example code here on my github repo. Ignore all files except:

  1. amd.html
  2. amd.js
  3. jquery-3.3.1.js
  4. require.js

However, when I access the page, whether using the file:/// protocol or using a web server, the module is not loaded and I see a blank page.

The console reports undefined for the console.log statement, and reports the following exception for the second statement where I access the jQuery object/function, and it is what gets returned from the module.

TypeError: $ is not a function

I am using jquery version 3.3.1. If you look at the source of this (and any) version of jquery, it is well known that jquery is a function object. See below:

From the jQuery source

define( [
    ...
], function( ..., ..., ... ) {

    jQuery = function( selector, context ) {

        return new jQuery.fn.init( selector, context );
    },

    return jQuery;
});

1 Answer 1

3

Did you enter 'jquery' into your requirejs config?

requirejs.config({
    baseUrl: 'js/lib', // path to your source
    paths: {
        jquery: 'jquery-3.3.1' // invoke
    }
});

enter image description here

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

3 Comments

No. I thought a config was optional and only required if you wanted to specify paths where paths were not on your local file system. For e.g. when you wanted to import a module from a CDN. Is this absolutely required. You mean require.js won't work without a config?
no your right, its only recommend to use the way it is intended. But certainly doesn't matter your correct!
also note according to requre.js webpage documentation it says - // THIS WILL NOT WORK define(['lib/jquery'], function ($) {...});

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.