General developer forum

Adding scripts onto the head

 
Picture of Jerry Zhao
Adding scripts onto the head
 

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: -
Picture of Amin Farajzadeh
Re: Adding scripts onto the head
 
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);
 
Average of ratings: -
Picture of Richard Oelmann
Re: Adding scripts onto the head
Core developersParticularly helpful MoodlersPlugin developersTesters

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.

 
Average of ratings: -
Picture of Jerry Zhao
Re: Adding scripts onto the head
 

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......

 
Average of ratings: -
Picture of Joao Almeida
Re: Adding scripts onto the head
 

Instead of using something like

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

try to use this

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

 
Average of ratings: -
Picture of Jerry Zhao
Re: Adding scripts onto the head
 

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. 

 
Average of ratings: -