How To Move JavaScript To Footer For WordPress

The most common comments or advise that you will get when you test your website at gtmetric or any web speed test website is to move your javascript to bottom of the page or under footer for wordpress.  This is because javascript is known as render-blocking script. What happened is, before a website being displayed in your browser, it will first build the DOM tree by parsing HTML markup. If in case it finds any javascript were required to load, the process will need to wait and execute the javascript to finish before it can continue load other html markup. This will cause a delay to your website to be load and display by the browser.

 

We do believe that today, lots of web are being developed using WordPress. as for this tutorial, we will focus on how to do this if you are using wordpress as your CMS.

 

You can do this by adding some codes to your function.php inside your wordpress theme. you may find below are the codes that can help you achieved the task.

function remove_head_scripts() {
remove_action('wp_head', 'wp_print_scripts');
remove_action('wp_head', 'wp_print_head_scripts', 9);
remove_action('wp_head', 'wp_enqueue_scripts', 1);

add_action('wp_footer', 'wp_print_scripts', 5);
add_action('wp_footer', 'wp_enqueue_scripts', 5);
add_action('wp_footer', 'wp_print_head_scripts', 5);
}
add_action( 'wp_enqueue_scripts', 'remove_head_scripts' );

If you are using cPanel as your web control panel, you should be able to do this by following below steps.

1. Login to your cPanel and click on your File Manager icon.

2. You browser will open a new tab with list of files and folders that you can manage.

3. access to your public_html folder and double click on assets folder. from here, you need to access your theme directory and select your current use theme.

4. click on function.php and edit it. go to the bottom of the file, paste above scripts and save.

That’s it, now when you access your website and open your inspect element menu, you will see most of your .js file being only loaded after your <head> </head> at the bottom of your <body></body>

Tips:

1. It is advisable to clear your browser cache before you access your website after you make the above changes.

2. If your web server are installed with mod_pagespeed, we suggest you disabled it first and try to access your website. Once you have verified it is working, then you can enabled it again.