Jquery not loading before local plugin

Re: Jquery not loading before local plugin

by Andrew Lyons -
Number of replies: 0
Picture of Core developers Picture of Moodle HQ Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers Picture of Testers

Hi Kimber,

I believe that the reason you're not seeing jQuery is because you're not calling the page header in your output.

If you look at a typical Moodle PHP file, you'll see that it does a couple of things:

  1. require the config.php file
  2. login and capability checks
  3. outputs the page header
  4. outputs the content
  5. outputs the page footer

If you don't output the header then we don't output the main HTML structure (e.g. the head, title, CSS, base JavaScript, etc.).

I would still recommend looking at the AMD loading mechanisms.

There are two stages to loading JS in Moodle:

  1. in the header we load the YUI, and requireJS loaders, and the jQuery code; and
  2. in the footer we make use of those loaders.

We generally don't advise using jQuery without using the loader.

Typically a use of the requireJS loader looks something like:

require(['local_foo/yourjsfilename'], function(amd) { amd.init([]); });

It's just a really basic use of the loader to load some other code which actually does the work.

To generate this, you need to have something in your PHP call:

$PAGE->requires->js_call_amd('local_foo/yourjsfilename', 'init');

In your JS file, which will be located at local/foo/amd/src/yourjsfilename.js, you write:

require(['jquery'], function($) {
  return {
    init: function() {
      // Your code here.
    }
  }
});

So essentially, in your case, you need to

  1. create the directory structure: local/tutorial/amd/src/
  2. create a file in that src folder (e.g. tutorial.js) and put the bigger block above in it, replacing 'Your code here.' with your code
  3. modify your file to include your code using the PAGE->requires code above.

Voila,

Andrew