How To Move JavaScript to WordPress Footer

How To Move JavaScript to WordPress Footer

The most common comments or advice that you will get when you test your website at the web speed test website is to move javascript to the bottom of the page or under the footer HTML tag.

Why must do this?

Simple answer. This is because javascript is known as a 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 to load other HTML markups. This will cause a delay to your website to be load and display by the browser.

We do believe that today, lots of webs 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 the below steps.

  1. Login to your cPanel and click on your File Manager icon.
  2. Your browser will open a new tab with a list of files and folders that you can manage.
  3. Access to your public_html folder and double click on the 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 is 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 enable it again.

 

Leave a Reply

Your email address will not be published. Required fields are marked *