WordPress: How to move script to footer if plugin doesn’t support it

Many WordPress plugins provide you with an option to configure whether scripts are loaded in the header or the footer of the page.

If you want to move a script to the footer for performance reasons, and the plugin doesn’t support it, one option is to just edit the wp_enqueue_script() call in the plugin’s source code and set $in_footer = true.

However, these change won’t survive plugin updates and hence are not recommended for security reasons.

A better option is to write a custom plugin that removes the <script> tag from the head and moves it to the footer. The following file is the functions.php of my custom plugin that moves the <script> tag from the cookie-law-info plugin to the bottom of the page.

<?php 
/*
Plugin Name: TechOverflow Cookie Law to footer
*/

function postpone_script($name) {
    global $wp_scripts;
    // Get attributes from original script
    $thesrc = $wp_scripts->registered[$name]->src;
    $theversion = $wp_scripts->registered[$name]->ver;
    // Remove script from the header
    wp_dequeue_script($name);
    wp_deregister_script($name);
    // Add script to the bottom
    wp_enqueue_script($name, $thesrc, false /* no deps */, $theversion, true /* bottom */);
}

/**
 * Move cookie law javascript to the bottom
 */
function postpone_cookie_law() {
    postpone_script('cookie-law-info');
}
    
add_action( 'wp_print_scripts', 'postpone_cookie_law' );

Just create an new folder called techoverflow-cookie-law-footer inside your wp-content/plugins directory, and save the source code listed above as wp-content/plugins/techoverflow-cookie-law-footer/functions.php inside. After that, you can modify the code to fit your specific needs.

Remember to check your page for issues (javascript errors, delayed rendering of some elements) that appear when you move the javascript to the footer, since some plugins may not be compatible with the script being placed in the footer. Also, you might need to call postpone_script() multiple scripts with different $name argument. Check the original plugin’s wp_enqueue_script() calls for the correct $name (first argument). In case it’s not obvious which wp_enqueue_script() call relates to a specific script, you can also check the version in the src of the original <script> tag (e.g. 1.8.2 in ...?ver=1.8.2 ) and search for that version in the plugin’s folder to find the matching wp_enqueue_script() call.