WordPress has an enqueuing system which allows developers to utilize the built-in JavaScript libraries rather than loading them multiple times. This helps avoid conflicts and reduces page load time.
Example:
function custom_scripts() {
wp_register_script(
'my_script',
plugins_url('my_script.js', __FILE__),
array('jquery'),
'1.0',
true);
wp_enqueue_script('my_script');
}
add_action( 'wp_enqueue_scripts', 'custom_scripts' );
First, we need to register a script to be enqueued by using a wp_register_script function. This function accepts 5 parameters:
- $handle – Handle is the unique name of your script.
- $src – The location of your script.
- $deps – An array of registered script handles this script depends on. If a script uses jQuery, you should add jQuery in the dependency area. It will be loaded if it has not been already done.
- $ver – This is the version number of your script. This parameter is optional.
- $in_footer – Set to true if you want to load your script in the footer. This parameter is optional and its default value is false, which loads the script in the header.
In the example above, we register a script with my_script name, which is located into the plugins folder and has a my_script.js filename. It is dependant on jQuery. The script has a version number of 1.0 and is loaded in the footer.
After providing all the parameters in wp_register_script, we just call the script in wp_enqueue_script() which enqueues it.
The last step is to use the wp_enqueue_scripts action hook to load the script. Despite its name, it is used for adding both scripts and styles in the front-end.
Leave A Comment