11

How can I add my script files to the very top in the wp_head?

From this guide, using the code below will always add my new script file to the very bottom:

add_action('wp_head','hook_javascript');

function hook_javascript() {

    $output="<script> alert('Page is loading...'); </script>";

    echo $output;
}

Any ideas how I can move my new script files to the top?

Run
  • 54,938
  • 169
  • 450
  • 748

2 Answers2

18

Use the $priority parameter of the add_action() function.

add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )

$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 value: 10

So, choose a very low number and as long as no other plugin/theme uses an even lower number your line will be added at the top.

add_action('wp_head','hook_javascript', -1000);
Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
6
function enqueue_assets()
{
    wp_enqueue_script('your_plugin_js', plugins_url('/my.js', __FILE__));
}
add_action('wp_enqueue_scripts', 'enqueue_assets');

By default, this will put it in the header. If you change your mind in the future (and you should), you can pass true as fifth parameter of wp_enqueue_script and it will be placed at the bottom. Refer to the documentation for more info on params.

Igor Yavych
  • 4,166
  • 3
  • 21
  • 42
  • 1
    I misunderstood your question a bit. Priority param should do the trick as author above has specified. Though there is no need to make it a negative value. – Igor Yavych Feb 28 '16 at 16:08