O'Reilly logo

Moodle JavaScript Cookbook by Alastair Hole

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Loading a JavaScript file

A majority of the JavaScript we add will be contained within an external JavaScript file, which is a text file with a .js extension. In this recipe, we will learn how to use the $PAGE object to include such a file.

Getting ready

Make a new PHP file named requirejs.php in the cook directory similar to the template in the previous recipe:

<?php
require_once(dirname(__FILE__) . '/../config.php');
$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM));
$PAGE->set_url('/cook/requirejs.php');
$PAGE->requires->js('/cook/alert.js');
echo $OUTPUT->header();
echo $OUTPUT->footer();
?>

Next, we create the accompanying JavaScript file, alert.js, with the following content:

alert('Hello World!');

Now when we load the page in a web ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required