How to enqueue a script after all other scripts in WordPress
By default, WordPress prints scripts in the order they are enqueued, taking dependencies into account. Sometimes a script must run last, after jQuery and everything that other plugins have added to the page. The dependency list, a late hook priority and the wp_footer hook give you full control over the order.
Problem: A JavaScript file needs to run after all other scripts on the page, for example an initialisation script that uses libraries registered by other plugins, but a standard wp_enqueue_script() call prints it too early.
Method 1: dependencies (the reliable way)
If you know which scripts yours depends on, list their handles in the $deps argument. WordPress guarantees they are printed before your script, regardless of priorities:
add_action( 'wp_enqueue_scripts', 'enqueue_last_script', 9999 );
function enqueue_last_script() {
wp_enqueue_script(
'my-last-script',
get_template_directory_uri() . '/js/last.js',
array( 'jquery', 'some-plugin-script' ), // printed before this script
'1.0.0',
true // load in the footer
);
}
Priority 9999 runs the callback after most other wp_enqueue_scripts callbacks (the default is 10), so the script also ends up late in the queue among scripts it does not depend on. Loading it in the footer puts it after all header scripts.
Method 2: print inline code at the very end
If the code must run literally at the end of the page, hook into wp_footer with the highest possible priority. Footer scripts are printed by wp_print_footer_scripts() at priority 20, so anything at PHP_INT_MAX comes after them:
add_action( 'wp_footer', 'print_very_last_script', PHP_INT_MAX );
function print_very_last_script() {
?>
<script>
// Runs after all enqueued scripts.
document.dispatchEvent( new Event( 'all-scripts-loaded' ) );
</script>
<?php
}
Other scripts can listen for the all-scripts-loaded event instead of guessing when everything is ready.
Check the current order
To see what runs on wp_footer and at which priority, print the registered callbacks as HTML comments (for debugging only, remove it afterwards):
add_action( 'wp_footer', function() {
global $wp_filter;
$hooks = $wp_filter['wp_footer']->callbacks ?? array();
ksort( $hooks );
foreach ( $hooks as $priority => $callbacks ) {
foreach ( $callbacks as $cb ) {
if ( is_array( $cb['function'] ) ) {
$class = is_object( $cb['function'][0] ) ? get_class( $cb['function'][0] ) : $cb['function'][0];
$name = $class . '::' . $cb['function'][1];
} else {
$name = is_string( $cb['function'] ) ? $cb['function'] : 'closure';
}
echo "<!-- wp_footer priority {$priority}: {$name} -->\n";
}
}
}, PHP_INT_MAX );
NOTE: Prefer dependencies over priority tricks whenever you know the scripts involved. A priority only decides when your callback runs; dependencies decide the actual print order.