There are basically 3 steps that you need to do in your themes functions.php in order to add a javascript file to your theme.
- Hook into wp_enqueue_scripts
- Register your script with or without dependencies
- Enqueue your script with or without a condition
Here is a snippet with a lot of comments that should break it down for you how to add a javascript file that is in your theme’s folder under /js.
<?php
/*
* add this to your themes functions.php
*/
// Hook your script adding funtion in to wp_enqueue_scripts
// Change 'lm' prefix to your theme's initials or something unique
add_action( 'wp_enqueue_scripts', 'lm_load_javascript_files' );
// the function that registers the custom javascript files
function lm_load_javascript_files() {
// register your script using wp_register_script
// variables with op_ are optional
// wp_register_script( $handle, $URI_src, $op_dependency_array, $op_version, $op_in_footer_boolean );
wp_register_script( 'owl-carousel', get_template_directory_uri() . '/js/owl.carousel.js', array('jquery'), '2.4', true );
wp_register_script( 'owl-carousel-instance', get_template_directory_uri() . '/js/owl-carousel-instance.js', array('owl-carousel'), '1.0', true );
// add your script to the queue using the handle
// dependencies declared in wp_register added automatically
// Option A: add to every page
wp_enqueue_script( 'owl-carousel-instance' );
// Option B: add only to front page
// if ( is_front_page() ) {
// wp_enqueue_script( 'owl-carousel-instance' );
//}
// Option C: add only to specific page
// if ( is_page( 'pageslug' ) ){
// wp_enqueue_script( 'owl-carousel-instance' );
//}
}
?>
In the case of a child theme
Instead Use get_template_directory_uri()
get_stylesheet_directory_uri()
when registering the script like this.
<?php
/*
* add this to your themes functions.php
*/
add_action( 'wp_enqueue_scripts', 'lm_load_javascript_files' );
function lm_load_javascript_files() {
wp_register_script( 'owl-carousel', get_stylesheet_directory_uri() . '/js/owl.carousel.js', array('jquery'), '2.4', true );
wp_register_script( 'owl-carousel-instance', get_stylesheet_directory_uri() . '/js/info-carousel-instance.js', array('owl-carousel'), '1.0', true );
wp_enqueue_script( 'owl-carousel-instance' );
}
?>
Optimize webpage speed by de-registering JavaScript
You can also de-register script where is not needed, even the script that was added by plugins. For example you can de-register contanct From 7 script on pages that it’s not being used.
add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 );
function my_deregister_javascript() {
if ( !is_page('Contact') ) {
wp_deregister_script( 'contact-form-7' );
}
}
Let me know if this post helped.
Good to know… I used to declare them in the header.php