Correctly Enqueuing Styles and Scripts in WordPress

Understand how to and more importantly why to register and enqueue your scripts and stylesheets in wordpress. If you do that then you’ll begin to understand the power and ease with which you can do much more creative things and create interactive webpages

Example of Code to enqueue stylesheets (only syntax)

add_action('wp_enqueue_scripts','load_custom_scripts');
function load_custom_scripts(){
 wp_register_style( $handle, $src, $deps, $ver, $media );
/* wp_enqueue_style( $handle, $src, $deps, $ver, $media ); */
  wp_enqueue_style( $handle, $src, $deps, $ver, $media );
  wp_register_script( $handle, $src, $deps, $ver, $in_footer ); 
/*  wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );  */
 wp_enqueue_script($handle);
}

In the holy book of wordpress you will see these two codes wp_register_style and wp_enqueue_style

wp_register_script and wp_enqueue_script

What is the difference?? I looked a round quite a bit. As you get familiar with wordpress you’ll understand the differences until then here’s the big one. wp_enqueue_(something) will add the script or style to wordpress output whereas wp_register_(something) keeps a record of the script but won’t enqueue it into the html output

Okay now lets talk $deps dependencies. We use this most often with javascript files. Suppose you’re using a framework such as bootsrap for your site. And you want to use the modal box option. So if you don’t have bootsrap in your site this will lead to an error.

If you have used wp_register_script to register bootstap in your site then if you’re calling your modal box or any other javascript functionality through say a main.js file in your theme or plugin you can use the dependency field to specify that bootstrap has to be enqueued using the dependency field. Below is an example that i hope makes things clear.

add_action ('wp_enqueue_styles','load_main_script');
function load_main_script()
{
/*  wp_register_script( $handle, $src, $deps, $ver, $in_footer ); */
wp_register_script( 'bootstrap', get_template_directory_uri().'/js/bootstrap.js', '', '', true );
wp_register_script( 'main', get_template_directory_uri().'/js/main.js', array('bootstrap'), '', true );
wp_enqueue_script('main');	
}
So even though you haven’t enqueued bootstrap because main.js requires(is depenendent on bootstrap.js) wordpress will automatically load bootstrap.js before main.js

Now to the the last part $in_footer just specifies if script should be loaded in the head of the document or the footer. A good practice is to load all possible scripts in the footer as this will generate a visible output for the user….Happy Coding

[digthis_social_share]

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.