[Solved] How wp_enqueue_script works in WordPress?
Being the most recommended process for associating JavaScript to WordPress pages,Wp enqueue script is used for calling the linked script files on the page at the correct time. It can be handled using a wp_register _script() function or can be provided with all parameters necessary to link a script.
Terminology:
<?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); ?>
Criterion:
$handle
(string) Name used as a handle for the script. If the string contains a ‘?’, the preceding part of the string would be referred as the registered handle, and the succeeding part would be appended to the URL.
$src
(string) URL to the script, e.g. http://example.com/wp-content/themes/my-theme/my-theme-script.js. To get a proper URL to local scripts, use plugins_url() for plugins andget_template_directory_uri() for themes. Remote scripts can be specified with a protocol-agnostic URL, e.g. //otherdomain.com/js/their-script.js. It is only required when the script with the given $handle hasn’t been registered with wp_register_script().
$deps
(array) Array of handles of all registered scripts that this script depends upon, such as these scripts must be loaded first. This parameter is required when the script with the given $handle hasn’t been registered using wp_register_script().
$ver
(string) String specifying the script version number, which is integrated towards the end of the path. If no version is specified, then WordPress automatically adds a version number equal to the current version of WordPress. In case set to null no version is added.
$in_footer
(boolean) These scripts are placed in of the HTML document. When the value of parameter is true, the script is placed before end tag. It needs the theme to have the wp_footer() template tag in the appropriate place.
For Example :
Link a Theme Script Which Depends on jQuery
JavaScript files which are integrated into themes mostly require other JavaScript files that should be loaded beforehand to utilize its functions or variables.Using this $deps parameter, the wp_enqueue_script() and wp_register_script() functions enables us to point the dependencies when registering a new script. Using this WordPress automatically links all the dependencies to the HTML page prior to be linked to new script. If the handles of these dependencies are not already registered, WordPress will not link the new script. This example displays the jQuery library for the custom_script.js theme script:
<?php
function my_scripts_meth
wp_enqueue_scri
‘custom-script’
get_stylesheet_
array( ‘jquery’ )
);
}
add_action( ‘wp_enqueue_scr
?>