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
No edit summary
Line 3: Line 3:
These guidelines can only be applied fully from Moodle 2.0 onwards, because they rely on our new API to facilitate use of JavaScript.
These guidelines can only be applied fully from Moodle 2.0 onwards, because they 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.
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_module/yui_lib.


==General principles==
==General principles==
Line 17: Line 17:
The only <script> tags in the HTML should be
The only <script> tags in the HTML should be
# <script src=... tags to include the necessary .js files.
# <script src=... tags to include the necessary .js files.
# Simple function calls to trigger initialisation. For example <script type="text/javascript">initialise_my_widget('some', 'data', 123);</script>.
# Simple function calls to trigger initialisation and pass data from PHP to JavaScript. For example <script type="text/javascript">initialise_my_widget('some', 'data', 123);</script>.
# 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>.
 
Even these small amounts of JS you should not output directly. They will be generated automatically by calls to the $PAGE->requries->js_init_call() API. See below for details.


You should not use old-fashioned onXXX="event_handler" attributes in the HTML. Use Modern DOM events. The YUI events library makes this easy.
You should not use old-fashioned onXXX="event_handler" attributes in the HTML. Use Modern DOM events. The YUI events library makes this easy.
Line 26: Line 27:
* The official JavaScript library for Moodle is [[Development:YUI|YUI]]. That may not be your favourite, but it's the one that was chosen after careful research, so live with it.
* The official JavaScript library for Moodle is [[Development:YUI|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 also has its own JavaScript library code, packaged into in various JavaScript modules.


* Moodle uses the '''TinyMCE''' HTML editor.
* Moodle uses the '''TinyMCE''' HTML editor.
Line 32: Line 33:
===When to include the JavaScript===
===When to include the JavaScript===


As per [http://developer.yahoo.com/performance/rules.html 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. (This is the default behaviour with Moodle's JavaScript handling functions.)
As per [http://developer.yahoo.com/performance/rules.html 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. (This is the default behaviour with Moodle's JavaScript handling functions like $PAGE->requries->js_init_call().)


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 increase the perceived page-load performance for users.
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 increase the perceived page-load performance for users.
Line 42: Line 43:
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.
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/mymod.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.
So, if you are writing a new module that needs its own JavaScript, try starting with with a single file mod/mymod/module.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==
==How to achive these general principles in Moodle==
Line 50: Line 51:
===Getting Moodle to load your JavaScript files===
===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 [http://phpdocs.moodle.org/HEAD/moodlecore/page_requirements_manager.html page_requirements_manager] class. You use it like this:
Everything required by the current page is tracked by the $PAGE->requires object, which is an instance of the [http://phpdocs.moodle.org/HEAD/moodlecore/page_requirements_manager.html page_requirements_manager] class defined in lib/outputrequirementslib.php.


<code php>
The most important method in this class is the ->js_init_call(...) method. You use it like this:
$PAGE->requires->js('mod/mymod/scripts.js');
</code>


By default, this will put the &lt;script> tag that loads the script at the end of the &lt;body> tag, as recommended. If you really must load the script sooner, use one of the following
<code php>  
<code php>  
// Load the js file from head.
$PAGE->requires->js_init_call('M.mod_mymod.init_something', array('some', 'data', 'from', 'PHP'));
// (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')->asap();
</code>
</code>


$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.
Note that this will implicitly load the JavaScript code in mod/mymod/module.js, and then call the M.mod_mymod.init_something function passing four string arguments 'some', 'data', 'from', 'PHP'. You can pass any PHP type as an argument. The PHP values are encoded with json_encode before being passed to JavaScript, so numbers, strings, arrays and objects all work.
 
===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.
Sometimes, the code in the JavaScript module mod/mymod/module.js may require some other JavaScript libraries to be loaded, or it may require some language strings. In that case you need to use the full form of js_init_call:


<code php>
<code php>
$PAGE->requires->yui_lib('autocomplete');
$jsmodule = array(
    'name'    => 'mod_mymod',
    'fullpath' => '/mod/mymod/module.js',
    'requires' => array('base', 'io', 'node', 'json'),
    'strings' => array(
        array('something', 'mymod'),
        array('confirmdelete', 'mymod'),
        array('yes', 'moodle'),
        array('no', 'moodle')
    )
);
$PAGE->requires->js_init_call('M.mod_mymod.init_something', array('some', 'data', 'from', 'PHP'), false, $jsmodule);
</code>
</code>
(Naturally, it would be a good idea to put the definition of the $jsmodule array somewhere central like in the locallib.php file.)
The libraries in the 'requires' sub-array are YUI3 (or YUI2) libraries.


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.
The strings are Moodle language strings. In order for Moodle to have correctly determined the user's language, you should only call js_init_call after the call to require_login, which sets the current course, and ensures the user is logged in.


Because some YUI libraries rely on associated CSS, and because CSS can only be included in the &lt;head> section of the HTML, you should try to call $PAGE->requires->yui_lib before &lt;head> is output, if at all possible. If your code does try to require a YUI library after the header has been printed, and if that YUI library requires some CSS, and exception will be thrown explaining the problem, so you will know it happened.
$PAGE->requires keeps track of which files have been included. For example if two other modules both require the YUI base module, then it is only included once.


===JavaScript coding style===
===JavaScript coding style===
Line 89: Line 93:
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.
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.
Do not pollute the global JavaScript name-space. Try to package your JavaScript into objects, and put all objects inside the global M object, like the M.mod_mymod example above.  
 
(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:
 
<code xml>
<!-- HTML code that will work with JavaScript disabled,
    perhaps with an id="mything" attribute on the main HTML tag. -->
<script type="text/javascript">
    init_my_script('perhaps some data', 'for example', 'mything');
</script>
</code>
 
The best way to generate this initialisation script is to use another feature of $PAGE->requires:
<code php>
$PAGE->requires->js_function_call('init_my_script',
        array('perhaps some data', 'for example', 'mything'));
</code>
 
Once again, by default the &lt;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). Note that the data passed from PHP to JavaScript is automatically escaped using json_encode, so you can pass arrays, objects, and strings containing special characters without worrying.
 
===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:
<code php>
$data = array(
    'value1' => $value1,
    'value2' => $value2,
);
$PAGE->requires->data_for_js('mymod_config', $data);
</code>
 
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:
<code php>
$PAGE->requires->string_for_js('tooltip', 'mymod');
</code>
If you make this call, then the JavaScript variable mstr.mymod.tooltip will hold the value of get_string('tooltip', 'mymod').


===Different in content when JavaScript is on or off===
===Different in content when JavaScript is on or off===
Line 179: Line 140:
We build the icon using DOM methods. The only problem is that as the JavaScript is loaded in the footer, there is a small delay before the icons appear. Since when the icons appear, they do not cause other content on the page to move around, that is OK. Also, this delayed appearance is becoming more common on the web. For example, on http://twitter.com/, some things only appear a moment after the main part of the page has finished loading.
We build the icon using DOM methods. The only problem is that as the JavaScript is loaded in the footer, there is a small delay before the icons appear. Since when the icons appear, they do not cause other content on the page to move around, that is OK. Also, this delayed appearance is becoming more common on the web. For example, on http://twitter.com/, some things only appear a moment after the main part of the page has finished loading.


However, it the delayed appearance is really a problem, then the only solution is to embed the JavaScript that generates the extra content in the middle of the HTML, using $PAGE->requires->js_function_call(...)->now();.
However, it the delayed appearance is really a problem, then the only solution is to embed the JavaScript that generates the extra content in the middle of the HTML, using the js_writer class.


====Content that only appears when the user does something, when JavaScript is on====
====Content that only appears when the user does something, when JavaScript is on====
Line 211: Line 172:
</code>
</code>


Of course, if you are following the above guidelines and putting most of your JavaScript in separate .js files, and using $PAGE->requiers->js_function_call/string_for_js/data_for_js for the rest, then you do not need to worry about this section.
Of course, if you are following the above guidelines and putting most of your JavaScript in separate .js files, and using $PAGE->requires->js_finit_call, then this is taken care of for you automatically.


==Testing==
==Testing==
Line 225: Line 186:
* [[Development:JavaScript functions]]
* [[Development:JavaScript functions]]
* [http://developer.yahoo.com/performance/rules.html Yahoo's Best Practices for Speeding Up Your Web Site]
* [http://developer.yahoo.com/performance/rules.html Yahoo's Best Practices for Speeding Up Your Web Site]
* [http://moodle.org/mod/forum/discuss.php?d=106312 Forum thread for discussing this proposal]


[[Category:Coding guidelines|JavaScript guidelines]]
[[Category:Coding guidelines|JavaScript guidelines]]

Revision as of 20:53, 13 June 2010

Template:Moodle 2.0

These guidelines can only be applied fully from Moodle 2.0 onwards, because they 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_module/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 and pass data from PHP to JavaScript. For example <script type="text/javascript">initialise_my_widget('some', 'data', 123);</script>.

Even these small amounts of JS you should not output directly. They will be generated automatically by calls to the $PAGE->requries->js_init_call() API. See below for details.

You should not use old-fashioned onXXX="event_handler" attributes in the HTML. Use Modern DOM events. The YUI events library makes this easy.

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, packaged into in various JavaScript modules.
  • 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. (This is the default behaviour with Moodle's JavaScript handling functions like $PAGE->requries->js_init_call().)

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 increase 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/module.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 defined in lib/outputrequirementslib.php.

The most important method in this class is the ->js_init_call(...) method. You use it like this:

$PAGE->requires->js_init_call('M.mod_mymod.init_something', array('some', 'data', 'from', 'PHP'));

Note that this will implicitly load the JavaScript code in mod/mymod/module.js, and then call the M.mod_mymod.init_something function passing four string arguments 'some', 'data', 'from', 'PHP'. You can pass any PHP type as an argument. The PHP values are encoded with json_encode before being passed to JavaScript, so numbers, strings, arrays and objects all work.

Sometimes, the code in the JavaScript module mod/mymod/module.js may require some other JavaScript libraries to be loaded, or it may require some language strings. In that case you need to use the full form of js_init_call:

$jsmodule = array(

   'name'     => 'mod_mymod',
   'fullpath' => '/mod/mymod/module.js',
   'requires' => array('base', 'io', 'node', 'json'),
   'strings' => array(
       array('something', 'mymod'),
       array('confirmdelete', 'mymod'),
       array('yes', 'moodle'),
       array('no', 'moodle')
   )

); $PAGE->requires->js_init_call('M.mod_mymod.init_something', array('some', 'data', 'from', 'PHP'), false, $jsmodule); (Naturally, it would be a good idea to put the definition of the $jsmodule array somewhere central like in the locallib.php file.)

The libraries in the 'requires' sub-array are YUI3 (or YUI2) libraries.

The strings are Moodle language strings. In order for Moodle to have correctly determined the user's language, you should only call js_init_call after the call to require_login, which sets the current course, and ensures the user is logged in.

$PAGE->requires keeps track of which files have been included. For example if two other modules both require the YUI base module, then it is only included once.

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.

Do not pollute the global JavaScript name-space. Try to package your JavaScript into objects, and put all objects inside the global M object, like the M.mod_mymod example above.

Different in content when JavaScript is on or off

Remember the overriding principals that everything should work with JavaScript off, and we should adopt a Progressive enhancement approach. However, there are valid reasons why sometimes you need different content with JavaScript is on or off. We can break it down into three cases:

Content that should only be visible with JavaScript off

An example of this is the automatic search when you are looking for a user to assign a role to. With JavaScript on, the search automatically starts after a delay. With JavaScript off, we want an explicit Search button visible.

To handle this case, Moodle automatically add a class 'jsenabled' to the body tag using JavaScript. So you just need to add a rule like body.jsenebled .mywidget .submitbutton {

   display: none;

} to the stylesheet, and the button will be invisible if JavaScript is enabled.

An alternative strategy is to remove the particular bits of HTML from the page using DOM methods. However, if your JavaScript is only loaded at the end of the page, it may take some time for the extra content to disappear, which leads to a disconcerting flicker in the page.

Yet another approach is the old-fashioned <noscript> tag.

Content that needs to be visible right away when JavaScript is on

An example is the [+] or [-] icon that can be used to expand/collapse each block if JavaScript is on.

We can divide this into two subcases:

Content generated by PHP code

Where the HTML for the JavaScript only widget is generated by PHP, we can make it invisible when JavaScript is off using just CSS: .mywidget {

   display: none;

} body.jsenabled .mywidget {

   display: block;

} However, it could be argued that this approach is not really progressive enhancement.

Content generated by JavaScript code

This is more in keeping with progressive enhancement, and this is the way that the expand/collapse block icon is handled.

We build the icon using DOM methods. The only problem is that as the JavaScript is loaded in the footer, there is a small delay before the icons appear. Since when the icons appear, they do not cause other content on the page to move around, that is OK. Also, this delayed appearance is becoming more common on the web. For example, on http://twitter.com/, some things only appear a moment after the main part of the page has finished loading.

However, it the delayed appearance is really a problem, then the only solution is to embed the JavaScript that generates the extra content in the middle of the HTML, using the js_writer class.

Content that only appears when the user does something, when JavaScript is on

An example of this is something like file picker dialog that appears when you add an image to some content in the HTML editor, or the one that pops up when you click 'Add new question' in the quiz editing interface.

We have the same two sub-cases:

Content generated by PHP code

In this case, you need to make sure the content is always covered by a display: none; rule in the CSS, but then when the user takes an action like clicking a button to reveal the extra content, you need to override that class name some how, perhaps my adding or removing a className using JavaScript.

Content generated by JavaScript code

In this case, there is no problem. When the use triggers the extra content to appear, it is constructed using DOM methods. There may be a tiny delay, but the chances are that it will hardly be noticeable to the human eye.

In the content generation may be slow (perhaps because it is waiting for an Ajax request) then you should display a progress icon. See, for example, the loading of the tooltip for help icons.

Don't break XHTML strict!

Remember that all Moodle output must be XHTML strict, and that means that the HTML output must be well-formed XML. Inline JavaScript is a great way to break that. (JavaScript uses the < and & symbols that must be escaped in XML.) Therefore any JavaScript inline in the HTML should be escaped in a CDATA section:

<script type="text/javascript"> //<![CDATA[

  // Your JavaScript code goes here.

//]]> </script>

Of course, if you are following the above guidelines and putting most of your JavaScript in separate .js files, and using $PAGE->requires->js_finit_call, then this is taken care of for you automatically.

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