Loading a JavaScript file in <head>
In the previous recipe we learned the standard method of including a JavaScript file at the end of the document's <body>
tag.
In this recipe, we will look at how to ensure our JavaScript file is included within the <head>
tag. There are numerous reasons why you would require your file be included within the <head>
, for example if you need to use document.write
to manually write <head>
content.
Note
If you are in any doubt, use the technique in the previous recipe. If you need to use the technique in this recipe, the chances are you will know exactly why.
Getting ready
Once again, open the Moodle PHP file where we will add our .js
file. We will use the simple example from the previous recipe as a basis, with the necessary changes:
<?php require_once(dirname(__FILE__) . '/../config.php'); $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $PAGE->requires->js('/cook/alert.js', true); $PAGE->set_url('/cook/requirejs_head.php'); echo $OUTPUT->header(); echo $OUTPUT->footer(); ?>
Now when we load the page, we see that our JavaScript alert is executed immediately, assuring us that our code is loading and executing correctly, as seen in the following screenshot:
Note that the page underneath is blank at this stage, as our JavaScript code is being run from the <head>
tag, before the rest of the page has loaded.
How to do it...
You will notice that this code is almost identical to that of the previous recipe. The key difference here is the parameters we have passed to the $PAGE->requires->js
method. We have passed a second optional parameter which determines whether or not the <script>
tag will be rendered within the document's <head>
tag. In this case, we set it to true
to ensure that the <script>
tag is rendered as such.
How it works...
We have called $PAGE->requires->js
again, this time with two parameters. The first is the path to the .js
file we wish to include. The second is a Boolean value which specifies whether or not to include the file from within the <head>
tag of the HTML page.
The <script>
tag that is rendered to the document is identical to that of the previous recipe, with the crucial difference that it is rendered within the <head>
tag, rather than at the end of the <body>
tag.