Note: You are currently viewing documentation for Moodle 4.0. Up-to-date documentation for the latest stable version of Moodle may be available here: JavaScript guidelines.

Development:JavaScript guidelines: Difference between revisions

From MoodleDocs
Line 95: Line 95:
Since your .js files should not actually do anything when they are loaded, you need some way to trigger them into action. Normally the best way to do this is to put a simple inline script in the HTML that just calls an initialisation function. Typically, you want the HTML page you generate to look like this:
Since your .js files should not actually do anything when they are loaded, you need some way to trigger them into action. Normally the best way to do this is to put a simple inline script in the HTML that just calls an initialisation function. Typically, you want the HTML page you generate to look like this:


<code html>
<code xml>
<!-- HTML code that will work with JavaScript disabled,
<!-- HTML code that will work with JavaScript disabled,
     perhaps with an id="mything" attribute on the main HTML tag. -->
     perhaps with an id="mything" attribute on the main HTML tag. -->

Revision as of 06:47, 15 June 2009

Template:Moodle 2.0

These guidelines can only be applied fully from Moodle 2.0 onwards, becuase the rely on our new API to facilitate use of JavaScript.

When writing JavaScript for earlier versions of Moodle, please try to follow these guidelines in spirit and use the require_js function in place of $PAGE->requires->js/yui_lib.

General principles

Moodle should be usable without JavaScript

Everything in Moodle should work with JavaScript turned off. This is important for accessibility, and in line with the principles of unobtrusive JavaScript and progressive enhancement.

Minimise inline JavaScript

Almost all JavaScript code should be in separate .js files. There should be the smallest possible amount of JavaScript inline in the HTML code of pages.

The only <script> tags in the HTML should be

  1. <script src=... tags to include the necessary .js files.
  2. Simple function calls to trigger initialisation. For example <script type="text/javascript">initialise_my_feature('some', 'data', 123);</script>.
  3. Variable definitions to transfer data from the PHP code to JavaScript. For example <script type="text/javascript">var moodle_cfg = {"modpixpath":"http:\/\/tim.moodle.local\/moodle\/mod","sesskey":"ZVNQiq7pHu","developerdebug":true};</script>.

JavaScript libraries

The official JavaScript library for Moodle is YUI. That may not be your favourite, but it's the one that was chosen after careful research, so live with it.

Moodle also has its own JavaScript library code, principally in lib/javascript-static.js.

Moodle uses the TinyMCE HTML editor.

When to include the JavaScript

As per Yahoo's best practice guidelines, load and execute the JavaScript as late as possible, ideally the script tags should be the last thing before the </body> close tag.

Since everything should work without JavaScript, load and initialising your scripts only after everything else on the page has loaded should not be a problem and will increased the perceived page-load performance for users.

Minimise the number of .js files

Try not to use too many different .js files. Each separate file that the browser has to load incurs an overhead.

On the other hand, organise the JavaScript logically to ease maintenance, and don't include large amounts of irrelevant JavaScript code. Code that is loaded but never used is a waste of time.

So, if you are writing a new module that needs its own JavaScript, try starting with with a single file mod/mymod/scripts.js. If you find that you are writing a lot of JavaScript that is only needed when the teacher edits your module, but is not needed by students, then consider splitting that code into a separate file like mod/mymod/edit.js, and only including it where needed.

How to achive these general principles in Moodle

The rest of this page explains how you can achieve the above goals.

Getting Moodle to load your JavaScript files

Everything required by the current page is tracked by the $PAGE->requires object, which is an instance of the page_requirements_manager class. You use it like this:

$PAGE->requires->js('mod/mymod/scripts.js');

By default, this will put the <script> tag that loads the script at the end of the <body> tag, as recommended. If you really must load the script sooner, use one of the following // Load the js file from head. // (This will throw an exception if head has already been output.) $PAGE->requires->js('mod/mymod/scripts.js')->in_head();

// Loads the js file as soon as possible (from head, if that has // not been output yet, otherwise output the script tag right here.) echo $PAGE->requires->js('mod/mymod/scripts.js')->in_head();

$PAGE->requires keeps track of which files have been included, so even if two different pieces of code request the same library, it is only loaded once.

Getting Moodle to load YUI libraries

Because YUI is the official JavaScript library for Moodle, there is a short cut syntax for loading the YUI libraries.

$PAGE->requires->yui_lib('autocomplete');

This knows about the dependencies between the JavaScript libraries, so the above code will actually load the five libraries yahoo, dom, event, datasource and autocomplete. It will also load the required CSS file autocomplete/assets/skins/sam/autocomplete.css.

Because some YUI libraries rely on associated CSS, and becuase CSS can only be included in the <head> section of the HTML, you should try to call $PAGE->requires->yui_lib before <head> is output, if at all possible.

JavaScript coding style

Moodle JavaScript code should should follow the same coding style as Moodle PHP code, allowing for the differences between PHP and JavaScript.

For example, all the rules on function_names, class_names and variablenames apply. You should document your code with JSDoc comments. Layout your JavaScript expressions and statements like the equivalent PHP ones.

Normally, your .js files should simply define things like functions, classes and variables. When the file is loaded, no JavaScript code should actually be executed that has any effect unless it is the sort of code that can safely be executed once per HTML page. This is so that it plays nicely with the require_once-like behaviour of $PAGE->requires->js.

Try to add as few things as possible to the global JavaScript name-space - use a few objects in the global name-space with properties and methods.

(An extreme example of this practice is the YUI libraries which only add a single YAHOO object to the global scope and put everything inside that. Moodle code does not need to go to that extreme - and do not add Moodle-specific code to the YAHOO namespace!)

Activating your JavaScript

Since your .js files should not actually do anything when they are loaded, you need some way to trigger them into action. Normally the best way to do this is to put a simple inline script in the HTML that just calls an initialisation function. Typically, you want the HTML page you generate to look like this:

<script type="text/javascript">

   init_my_script('perhaps some data', 'for example', 'mything');

</script>

The best way to generate this initialisation script is to use another feature of $PAGE->requires: $PAGE->requires->js_function_call('init_my_script',

       array('perhaps some data', 'for example', 'mything'));

Once again, by default the <script> tag will be generated at the end of the HTML, but you can change that with modifiers like ->asap() or ->on_dom_ready() (which uses the YUI onDomReady event).

Getting more variables from PHP to JavaScript

The arguments you pass to the initialisation function are one way to get specific data from your PHP code to your JavaScript. However, when you need to initialise several things on the page and they all need the same data, there is a better way: $data = array(

   'value1' => $value1,
   'value2' => $value2,

); $PAGE->requires->data_for_js('mymod_config', $data);

If you do that, then in JavaScript, mymod_config.value1 will contain the value of the PHP variable $value1.

Getting language strings from PHP to JavaScript

One type of value you frequently need to get from PHP to JavaScript is the translation of some language strings into the current language. Because this is a common requirement, there is a special syntax for this: $PAGE->requires->data_for_js('tooltip', 'mymod'); If you make this call, then the JavaScript variable mstr.mymod.tooltip will hold the value of get_string('tooltip', 'mymod').

Other points

When JavaScript is turned on, the class name 'jsenabled' will be added to the body tag of the page. You can use this if, for example, you have some content that you wish to be hidden when JavaScript is enabled. Just add .jsenabled .nonjsfallback {

   display: none;

}

Testing

JavaScript support varies a lot between browsers. JavaScript needs to be tested in IE, Firefox and Safari. Ideally, Moodle will support all the browsers that YUI does.

See also

Template:CategoryDeveloper