How To Enqueue JavaScript in Footer of WordPress Theme

If you are looking for something which will help you to load or enqueue the JavaScript in Footer of WordPress theme then this post can help you out.

You know its a good practice to load all of your theme’s CSS (Cascading Style Sheet) in the header while all the JS (JavaScript) in the footer. Some call it the golden rule.

But its true that adding JavaScript to the Theme’s Footer can dramatically help to improve the page speed. Lets see how to do that –

First we will create a function, understand it and then make the necessary changes to make it work.

#1) Creating A Function

Go to your theme’s functions.php file . It can be accessed by browsing through Admin Dashboard > Appearance > Editor > Functions.php. Inside this file add the following piece of code.

[php]

function my_scripts_method() {

wp_enqueue_script(‘myscript1’, get_template_directory_uri() . ‘/js/myscript1.js’, array(‘jquery’), false);

wp_enqueue_script(‘myscript2’, get_template_directory_uri() . ‘/js/myscript2.js’, array(‘jquery’), false, true);

}

add_action(‘wp_enqueue_scripts’, ‘my_scripts_method’);

[/php]

#2) Understanding The Function

We have created a function name my_scripts_method. When this function is called, it will execute two statements inside it which are nothing but wp_enqueue_script() functions.

First statement adds myscript1.js file inside the header of your WordPress theme.

While the Second statement adds myscript2.js file inside the footer of your WordPress theme.

Now you can skip to 3rd point if you don’t want additional info –

The wp_enqueue_script() function has 5 parameters which are name, path_to_file, depends_on_which_script, version, header_or_footer.

In first function we have only four parameters and since the last parameter is missing, its assumed false by default. If the last parameter is false then JavaScript will be loaded inside the header. But if the last parameter (5th parameter) is true then JavaScript is loaded in footer.

#3) Modifying The Function

In the code given above, you have to just replace myscript1 and myscript2 with your desired JavaScript file name. Also note that you have to place the file inside the your_theme/js folder.

If your theme name is XYZ then you will have to place or upload JavaScript at –

yourdomain/wp-content/themes/XYZ/js/

And of course, save the functions.php file after adding the code.

I hope this helps. For more amazing posts do subscribe to blog feed.

1 Comment

Leave a Reply

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