Adding scripts onto the head

Adding scripts onto the head

by Jerry Zhao -
Number of replies: 5

Hi there,

I am trying to add scripts onto the head and I came across this solution

$PAGE->requires->js( new moodle_url($CFG->wwwroot . 'http://code.jquery.com/jquery-3.2.1.min.js'));

However, this only loads into the body and not the head. Is there anyway around this? (The url cannot change)


Thank you!

Average of ratings: -
In reply to Jerry Zhao

Re: Adding scripts onto the head

by Amin Farajzadeh -
use this for add script to head:

$PAGE->requires->js( new moodle_url($CFG->wwwroot . 'http://code.jquery.com/jquery-3.2.1.min.js') , true);
In reply to Amin Farajzadeh

Re: Adding scripts onto the head

by Richard Oelmann -
Picture of Core developers Picture of Plugin developers Picture of Testers

I'm struggling to see how either option would work - but happy to learn please...

Surely $CFG->wwwroot . 'http://code.jquery.com/jquery-3.2.1.min.js' just concatenates the moodle site wwwroot and the external url and gives a link that doesn't have any chance of working at all...

This is what I get on my local host if I add that line:

<script type="text/javascript" src="http://localhost/moodledevhttp://code.jquery.com/jquery-3.2.1.min.js"></script>
So, there is no way it will work, whether in body or head.

Try taking out the $CFG->wwwroot . and see of it works then.

In reply to Richard Oelmann

Re: Adding scripts onto the head

by Jerry Zhao -

Thanks for the replies. I have tried both ways and the script tag don't show up anymore for either. I think it's the ,true parameter that is making it happen. If I get rid of that, the script tag at least get appended to the end of my body. 

What's weird is that even after the page loads and I see the script tag being appended to the end of the body, I cannot use jQuery in the console. It just says $ is undefined......

In reply to Jerry Zhao

Re: Adding scripts onto the head

by Joao Almeida -

Instead of using something like

$(function() {
// Document is ready
});

try to use this

jQuery(function( $ ) {
// Your code using failsafe $ alias here...
})

In reply to Joao Almeida

Re: Adding scripts onto the head

by Jerry Zhao -

Thank you!

This worked for jQuery. However, I want to use not just jQuery, but some custom scripts as well..And setting js(moodle_url, true) to true doesn't seem to work for me.