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 browser, we see that the JavaScript alert is displayed as shown in the following screenshot, proving to us that our code has loaded and executed correctly:
Note that we see the Home button, meaning that the footer of the page has loaded. This is because our code is executed at the end of the <body>
tag.
How to do it...
We have created a page based on the blank template we created in the first recipe of this chapter. To this, we have added the following line:
$PAGE->requires->js('/cook/alert.js');
How it works...
We are making use of the Page Requirements Manager, $PAGE
, which is an object that contains various methods for setting up additional components for a page. Here we have called the $PAGE->requires->js
method, and passed the path to our .js
file as a parameter.
Moodle then adds this script to the list of scripts to be included within the final rendered page. A <script>
tag similar to the following will be inserted just before the closing <body>
tag:
<script type="text/javascript" src="http://localhost/moodle/lib/javascript.php? file=%2Fcook%2Falert.js&rev=1"></script>
Note
The <script>
tag is inserted at the end of the <body>
tag, inline with the current best practice, offering the best page performance and a simplification of handling DOM-ready events among other reasons. For a fuller discussion of this technique, please refer to the Yahoo! Developer Network resource at the following URL:
http://developer.yahoo.com/performance/rules.html#js_bottom
This code must be included after the Moodle configuration file config.php
has been included. This is where the $PAGE
object is setup for us.