Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enqueue Wordpress plugin scripts below all other JS

I am developing a simple Wordpress app but I am having an issue as all of the plugin scripts are rendered before those which are enqueued in my functions.php.

Here is a sample section of the functions.php:

function my_scripts() {
    wp_register_script('app-js', get_template_directory_uri() . '/javascripts/app.js', array('jquery'), null, true );
    wp_enqueue_script('app-js');
}
add_action( 'wp_enqueue_scripts', 'my_scripts');

The important this to note is that (following best practice my JS is set to render at the bottom of the page.

I also have couple of plugins running on the theme. The problem is that the output looks like this:

<!-- Note the plugin appears first -->
<script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/my-plugin/acl-plugin.js'></script>
<!-- And the main JS appears second -->
<script type='text/javascript' src='http://localhost/wordpress/wp-content/themes/my-theme/javascripts/app.js'></script>
</body>
</html>

How can I force Wordpress to display the main JS (which i believe is rendered by wp_head() to appear at the very bottom of the page?

like image 831
Sheixt Avatar asked Nov 11 '13 19:11

Sheixt


1 Answers

The WordPress wp_head() method will only output scripts or styles that have that last parameter in the WordPress wp_enqueue_script() set to false.. when it is set to true it will render in the footer via the wp_footer()

you can change the priority of when its called and inserted by adjusting the $priority parameter in the add_action()

http://codex.wordpress.org/Function_Reference/add_action

$priority (int) (optional) Used to specify the order in which the functions associated with a particular action are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action. Default: 10

add_action( $hook, $function_to_add, $priority, $accepted_args );

And also look at the following two WordPress methods:

wp_enqueue_script() :

https://developer.wordpress.org/reference/functions/wp_enqueue_script/

wp_enqueue_script( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )

wp_register_script() :

https://developer.wordpress.org/reference/functions/wp_register_script/

wp_register_script( string $handle, string $src, array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )

Try this..

You might have to play with that $priority parameter

function my_scripts() {
        wp_register_script('app-js', get_template_directory_uri() . '/javascripts/app.js', array('jquery'), null, true );
        wp_enqueue_script('app-js');
}
add_action( 'wp_enqueue_scripts', 'my_scripts', 20, 1);
like image 129
Jonathan Marzullo Avatar answered Oct 04 '22 03:10

Jonathan Marzullo