wp_enqueue_script()WP 2.1.0

Adds a script (JavaScript file) to the page.

It is important to use this function to add JS files because with it you can merge several JS files into one without further problems. Also, it helps you to get rid of script conflicts when the dependent script is connected after the one from which it depends.

The function adds a script only if it has not been added yet and if the other scripts on which it depends are registered. Dependent scripts are added (connected) automatically.

IMPORTANT! This function may not work if wp_head() and wp_footer() functions are not used in your theme. It's because the scripts are loaded on actions (hooks) created by these functions.

Also, this function must be called before wp_footer(), otherwise scripts will not be connected at all.

If the script is already registered with wp_register_script() then you can enqueue it by its identifier ($handle).

// jquery is registered in WP by default.
// So you can enqueue it just by its identifier:
wp_enqueue_script('jquery');

If the script isn't registered, then you can register and enqueue it just with this function.

 wp_enqueue_script('newscript', get_template_directory_uri() . '/js/custom_script.js');

Since version 3.3 this function can be used during the page generation. In this case, the enqueued script will be loaded in the footer of the page when the hook wp_footer is called.

Usually the function is hooked on one of these actions:

Return

null. Nothing (null).

Usage

wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
$handle(string) (required)

Name of the script. Should be unique. In lowercase.

If the string contains a question mark (?): scriptaculous?v=1.2, then the preceding part will be the name of the script, and all that text after the question mark will be added to the URL as request parameters. So you can, for example, specify the version of the script.

$src(string)

Full URL of the script, or path of the script relative to the WordPress root directory. For example:
http://example.com/wp-content/themes/my-theme/my-theme-script.js.

This option is only needed when the script is not registered and WordPress is not yet aware of it and its path. see wp_register_script().

There's no need to specify a hardcoded path, use the following functions:

External domains can be specified with implicit protocol //example.com/js/their-script.js

See below the list of all registered scripts by default (like jquery).

Default: ''

$deps(array)
An array of registered script handles this script depends on. Scripts that must be loaded before this one.
Default: array()
$ver(string/true/false/null)

String specifying script version number. The version is added to the URL as a query string for cache busting purposes.

If set to false, the current WordPress version will be used.

If set to null, version adding will be skipped.

Default: false

$in_footer(true/false)

Whether to enqueue the script in the footer?

Typically, a script is included in the <head> of the document, if set to true, the script will be included before the </body> tag (where the wp_footer() template tag is called).

If due to the dependence on other scripts, there is no way to connect the current script in the footer, this parameter will be ignored.

For clear code, you may specify any string instead of true, for example, you can use 'in_footer'.

Default: false

Examples

3

#1 Load the regular WP script 'scriptaculous'.

// For frontend of the site
add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); 

function my_scripts_method() {
	wp_enqueue_script( 'scriptaculous' );            
}
0

#2 Download the base WordPress script from a non-standard address.

For example if you want to replace the default jquery script with a CDN-version, add this code to the functions.php:

add_action( 'wp_enqueue_scripts', 'my_scripts_method', 11 );
function my_scripts_method() {
	wp_deregister_script( 'jquery' );
	wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' );
	wp_enqueue_script( 'jquery' );
}    

Using the wp_enqueue_scripts filter (instead of init as recommended on some resources), we avoid registering an alternative version of jQuery on the dashboard, what (among other things) reduces the risk of disruption of the wp-editor.

0

#3 Register and enqueue a custom script, which depends on jQuery

Register and enqueue a custom script that depends on jquery (so it will be loaded before this script).

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
function my_scripts_method() {
	$script_url = plugins_url( '/js/newscript.js', __FILE__ );
	wp_enqueue_script('custom-script', $script_url, array('jquery') );
}
0

#4 Enqueue a script only for specific types of pages

For example you need conditional tags for loading script scriptaculous. You can use hook wp because conditionals tags available after it.

add_action( 'wp', 'add_my_script_where_it_necessery' );
function add_my_script_where_it_necessery(){
	if( is_single() )
		add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
}
function my_scripts_method() {
	$script_url = plugins_url( '/js/newscript.js', __FILE__ );
	wp_enqueue_script( 'newscript', $script_url, ['scriptaculous'] );
}
0

#5 Enqueue a script that depends on a default script

Specify the name of the dependency in the third argument.

Often it is required that another JavaScript file be loaded before the JavaScript files that come with the design theme. WordPress provides an API that allows you to specify its dependencies when registering a script. For example, the theme with the code below requires that the jQuery library be loaded before the custom_script.js script:

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

function my_scripts_method() {

	wp_enqueue_script( 'custom-script',
		get_template_directory_uri() . '/js/custom_script.js',
		array( 'jquery' )
	);
}
0

#6 Loading plugin scripts only on its pages

add_action( 'admin_menu', 'my_plugin_admin_menu' );
function my_plugin_admin_menu() {
	// Register plugin page
	$page = add_submenu_page(
		'edit.php',                     
		__( 'My plugin', 'myPlugin' ),  
		__( 'My plugin', 'myPlugin' ),  
		'manage_options',               
		'my_plugin-options',            
		'my_plugin_manage_menu'         
	);

	// Connect to a needed hook using the plugin page identifier 
	add_action( 'load-' . $page, 'my_plugin_admin_scripts' );
}

// This function will be called only on the page of the plugin
function my_plugin_admin_scripts() {
	wp_enqueue_script( 'my-plugin-script', plugins_url('/script.js', __FILE__) );
}

function my_plugin_manage_menu() {
	// page code
}
0

#7 Dynamic file version detection

To change file URL when the file content changed in order to disable browser cache, you can specify file version dynamically base on file modification time (filemtime):

add_action('wp_enqueue_scripts', 'my_scripts_method');
function my_scripts_method() {
	wp_enqueue_script( 'custom-script',
		get_template_directory_uri() . '/js/custom_script.js',
		[ 'jquery' ],
		filemtime( get_theme_file_path('js/custom_script.js') )
	);
}

filemtime() performance is very high - on SSD disk 0.5 sec for 50K iterations - it's very fast!

0

#8 Remove a version of the script or style from the URL

When registering a script, it gets a version (the current version of WordPress, by default): /wp-includes/css/dashicons.min.css?ver=4.9. You can remove it:

// Removing all versions of all scripts (and styles):
add_filter( 'script_loader_src', '_remove_script_version' );
add_filter( 'style_loader_src', '_remove_script_version' );
function _remove_script_version( $src ){
	$parts = explode( '?', $src );
	return $parts[0];
}

Remove only WordPress versions:

add_filter( 'script_loader_src', 'hb_remove_wp_version_from_src' );
add_filter( 'style_loader_src', 'hb_remove_wp_version_from_src' );
function hb_remove_wp_version_from_src( $src ) {
	 global $wp_version;
	 parse_str( parse_url( $src, PHP_URL_QUERY ), $query );
	 if ( ! empty($query['ver']) && $query['ver'] === $wp_version ) {
		  $src = remove_query_arg('ver', $src);
	 }
	 return $src;
}
0

#9 How to connect jquery from Google

Read in separate article.

Default WordPress 5.2.2 scripts

Name ID Dependences
  utils  
WP Common common jquery, hoverIntent, utils
  wp-a11y jquery
Simple AJAX Code-Kit sack  
QuickTags quicktags  
ColorPicker (deprecated) colorpicker prototype
  editor utils, jquery
  clipboard  
  wp-fullscreen-stub  
WordPress AJAX Response wp-ajax-response jquery
  wp-api-request jquery
  wp-pointer jquery-ui-widget, jquery-ui-position
Autosave autosave heartbeat
Heartbeat heartbeat jquery, wp-hooks
  wp-auth-check heartbeat
List Manipulation wp-lists wp-ajax-response, jquery-color
  prototype  
  scriptaculous-root prototype
  scriptaculous-builder scriptaculous-root
  scriptaculous-dragdrop scriptaculous-builder, scriptaculous-effects
  scriptaculous-effects scriptaculous-root
  scriptaculous-slider scriptaculous-effects
  scriptaculous-sound scriptaculous-root
  scriptaculous-controls scriptaculous-root
  scriptaculous scriptaculous-dragdrop, scriptaculous-slider, scriptaculous-controls
  cropper scriptaculous-dragdrop
jQuery jquery jquery-core, jquery-migrate
  jquery-core  
  jquery-migrate  
jQuery UI Core jquery-ui-core jquery
jQuery UI Effects jquery-effects-core jquery
jQuery UI Effects - Blind jquery-effects-blind jquery-effects-core
jQuery UI Effects - Bounce jquery-effects-bounce jquery-effects-core
jQuery UI Effects - Clip jquery-effects-clip jquery-effects-core
jQuery UI Effects - Drop jquery-effects-drop jquery-effects-core
jQuery UI Effects - Explode jquery-effects-explode jquery-effects-core
jQuery UI Effects - Fade jquery-effects-fade jquery-effects-core
jQuery UI Effects - Fold jquery-effects-fold jquery-effects-core
jQuery UI Effects - Highlight jquery-effects-highlight jquery-effects-core
  jquery-effects-puff jquery-effects-core, jquery-effects-scale
jQuery UI Effects - Pulsate jquery-effects-pulsate jquery-effects-core
jQuery UI Effects - Scale jquery-effects-scale jquery-effects-core, jquery-effects-size
jQuery UI Effects - Shake jquery-effects-shake jquery-effects-core
  jquery-effects-size jquery-effects-core
jQuery UI Effects - Slide jquery-effects-slide jquery-effects-core
jQuery UI Effects - Transfer jquery-effects-transfer jquery-effects-core
jQuery UI Accordion jquery-ui-accordion jquery-ui-core, jquery-ui-widget
jQuery UI Autocomplete jquery-ui-autocomplete jquery-ui-menu, wp-a11y
jQuery UI Button jquery-ui-button jquery-ui-core, jquery-ui-widget
jQuery UI Datepicker jquery-ui-datepicker jquery-ui-core
jQuery UI Dialog jquery-ui-dialog jquery-ui-resizable, jquery-ui-draggable, jquery-ui-button, jquery-ui-position
jQuery UI Draggable jquery-ui-draggable jquery-ui-mouse
jQuery UI Droppable jquery-ui-droppable jquery-ui-draggable
jQuery UI Menu jquery-ui-menu jquery-ui-core, jquery-ui-widget, jquery-ui-position
jQuery UI Mouse jquery-ui-mouse jquery-ui-core, jquery-ui-widget
jQuery UI Position jquery-ui-position jquery
jQuery UI Progressbar jquery-ui-progressbar jquery-ui-core, jquery-ui-widget
jQuery UI Resizable jquery-ui-resizable jquery-ui-mouse
jQuery UI Selectable jquery-ui-selectable jquery-ui-mouse
jQuery UI Selectmenu jquery-ui-selectmenu jquery-ui-menu
jQuery UI Slider jquery-ui-slider jquery-ui-mouse
jQuery UI Sortable jquery-ui-sortable jquery-ui-mouse
jQuery UI Spinner jquery-ui-spinner jquery-ui-button
jQuery UI Tabs jquery-ui-tabs jquery-ui-core, jquery-ui-widget
jQuery UI Tooltips jquery-ui-tooltip jquery-ui-core, jquery-ui-widget, jquery-ui-position
jQuery UI Widget jquery-ui-widget jquery
jQuery Form jquery-form jquery
jQuery Color jquery-color jquery
jQuery Schedule schedule jquery
  jquery-query jquery
  jquery-serialize-object jquery
jQuery Hotkeys jquery-hotkeys jquery
  jquery-table-hotkeys jquery, jquery-hotkeys
  jquery-touch-punch jquery-ui-widget, jquery-ui-mouse
jQuery Suggest suggest jquery
  imagesloaded  
Masonry (native Javascript) masonry imagesloaded
jQuery Masonry jquery-masonry jquery, masonry
ThickBox thickbox jquery
Jcrop jcrop jquery
SWFObject swfobject  
  moxiejs  
Plupload Core plupload moxiejs
Plupload All Runtimes plupload-all plupload
Plupload HTML5 plupload-html5 plupload
Plupload Flash plupload-flash plupload
Plupload Silverlight plupload-silverlight plupload
Plupload HTML4 plupload-html4 plupload
  plupload-handlers plupload, jquery
  wp-plupload plupload, jquery, json2, media-models
SWFUpload swfupload  
  swfupload-all swfupload
SWFUpload Handlers swfupload-handlers swfupload-all, jquery
Threaded Comments comment-reply  
JSON for JS json2  
Underscore js underscore  
Backbone js backbone underscore, jquery
  wp-util underscore, jquery
  wp-sanitize jquery
  wp-backbone backbone, wp-util
  revisions wp-backbone, jquery-ui-slider, hoverIntent
  imgareaselect jquery
  mediaelement jquery, mediaelement-core, mediaelement-migrate
  mediaelement-core  
  mediaelement-migrate  
  mediaelement-vimeo mediaelement
MediaElement.js (WP 3.6+) wp-mediaelement mediaelement
  wp-codemirror  
  csslint  
  esprima  
  jshint esprima
  jsonlint  
  htmlhint  
  htmlhint-kses htmlhint
  code-editor jquery, wp-codemirror, underscore
  wp-theme-plugin-editor wp-util, wp-sanitize, jquery, jquery-ui-core, wp-a11y, underscore
  wp-playlist wp-util, backbone, mediaelement
  zxcvbn-async  
Password Strength Meter password-strength-meter jquery, zxcvbn-async
  user-profile jquery, password-strength-meter, wp-util
  language-chooser jquery
  user-suggest jquery-ui-autocomplete
  admin-bar  
  wplink jquery, wp-a11y
  wpdialogs jquery-ui-dialog
Word Count word-count  
Media Upload media-upload thickbox, shortcode
jQuery HoverIntent hoverIntent jquery
  customize-base jquery, json2, underscore
  customize-loader customize-base
  customize-preview wp-a11y, customize-base
  customize-models underscore, backbone
  customize-views jquery, underscore, imgareaselect, customize-models, media-editor, media-views
  customize-controls customize-base, wp-a11y, wp-util, jquery-ui-core
  customize-selective-refresh jquery, wp-util, customize-preview
  customize-widgets jquery, jquery-ui-sortable, jquery-ui-droppable, wp-backbone, customize-controls
  customize-preview-widgets jquery, wp-util, customize-preview, customize-selective-refresh
  customize-nav-menus jquery, wp-backbone, customize-controls, accordion, nav-menu
  customize-preview-nav-menus jquery, wp-util, customize-preview, customize-selective-refresh
  wp-custom-header wp-a11y
  accordion jquery
  shortcode underscore
  media-models wp-backbone
  wp-embed  
  media-views utils, media-models, wp-plupload, jquery-ui-sortable, wp-mediaelement, wp-api-request
  media-editor shortcode, media-views
  media-audiovideo media-editor
  mce-view shortcode, jquery, media-views, media-audiovideo
  wp-api jquery, backbone, underscore, wp-api-request
  react wp-polyfill
  react-dom react
  moment  
  lodash  
  wp-polyfill-fetch  
  wp-polyfill-formdata  
  wp-polyfill-node-contains  
  wp-polyfill-element-closest  
  wp-polyfill  
  wp-tinymce-root  
  wp-tinymce wp-tinymce-root
  wp-tinymce-lists wp-tinymce
  wp-api-fetch wp-polyfill, wp-i18n, wp-url, wp-hooks
  wp-annotations wp-data, wp-hooks, wp-i18n, wp-polyfill, wp-rich-text
  wp-autop wp-polyfill
  wp-blob wp-polyfill
  wp-blocks wp-autop, wp-blob, wp-block-serialization-default-parser, wp-data, wp-dom, wp-element, wp-hooks, wp-html-entities, wp-i18n, wp-is-shallow-equal, wp-polyfill, wp-shortcode, lodash
  wp-block-library editor, lodash, wp-api-fetch, wp-autop, wp-blob, wp-block-editor, wp-blocks, wp-components, wp-compose, wp-core-data, wp-data, wp-date, wp-editor, wp-element, wp-html-entities, wp-i18n, wp-keycodes, wp-polyfill, wp-url, wp-viewport, wp-rich-text
  wp-block-serialization-default-parser  
  wp-block-editor lodash, wp-a11y, wp-blob, wp-blocks, wp-components, wp-compose, wp-core-data, wp-data, wp-dom, wp-element, wp-hooks, wp-html-entities, wp-i18n, wp-is-shallow-equal, wp-keycodes, wp-rich-text, wp-token-list, wp-url, wp-viewport, wp-wordcount
  wp-components lodash, moment, wp-a11y, wp-api-fetch, wp-compose, wp-dom, wp-element, wp-hooks, wp-html-entities, wp-i18n, wp-is-shallow-equal, wp-keycodes, wp-polyfill, wp-rich-text, wp-url
  wp-compose lodash, wp-element, wp-is-shallow-equal, wp-polyfill
  wp-core-data lodash, wp-api-fetch, wp-data, wp-deprecated, wp-polyfill, wp-url
  wp-data lodash, wp-compose, wp-element, wp-is-shallow-equal, wp-polyfill, wp-priority-queue, wp-redux-routine
  wp-date moment, wp-polyfill
  wp-deprecated wp-polyfill, wp-hooks
  wp-dom lodash, wp-polyfill
  wp-dom-ready wp-polyfill
  wp-edit-post jquery, lodash, postbox, media-models, media-views, wp-a11y, wp-api-fetch, wp-block-editor, wp-block-library, wp-blocks, wp-components, wp-compose, wp-core-data, wp-data, wp-dom-ready, wp-editor, wp-element, wp-embed, wp-i18n, wp-keycodes, wp-notices, wp-nux, wp-plugins, wp-polyfill, wp-url, wp-viewport
  wp-editor lodash, wp-api-fetch, wp-blob, wp-block-editor, wp-blocks, wp-components, wp-compose, wp-core-data, wp-data, wp-date, wp-deprecated, wp-element, wp-hooks, wp-html-entities, wp-i18n, wp-keycodes, wp-notices, wp-nux, wp-polyfill, wp-url, wp-viewport, wp-wordcount
  wp-element wp-polyfill, react, react-dom, lodash, wp-escape-html
  wp-escape-html wp-polyfill
  wp-format-library wp-block-editor, wp-components, wp-editor, wp-element, wp-i18n, wp-keycodes, wp-polyfill, wp-rich-text, wp-url
  wp-hooks wp-polyfill
  wp-html-entities wp-polyfill
  wp-i18n wp-polyfill
  wp-is-shallow-equal wp-polyfill
  wp-keycodes lodash, wp-polyfill, wp-i18n
  wp-list-reusable-blocks lodash, wp-api-fetch, wp-components, wp-compose, wp-element, wp-i18n, wp-polyfill
  wp-notices lodash, wp-a11y, wp-data, wp-polyfill
  wp-nux wp-element, lodash, wp-components, wp-compose, wp-data, wp-i18n, wp-polyfill, lodash
  wp-plugins lodash, wp-compose, wp-element, wp-hooks, wp-polyfill
  wp-priority-queue  
  wp-redux-routine wp-polyfill
  wp-rich-text lodash, wp-data, wp-escape-html, wp-polyfill
  wp-shortcode wp-polyfill, lodash
  wp-token-list lodash, wp-polyfill
  wp-url wp-polyfill
  wp-viewport wp-polyfill, wp-element, wp-data, wp-compose, lodash
  wp-wordcount wp-polyfill

This list is abtained from $GLOBALS['wp_scripts'] global variable. Registered scripts may vary depending on the page you are on. In the admin list will be longer.

For details, refer to the wp_default_scripts() function code.

Changes

Since version 3.5, WordPress has a new convention for minified scripts and styles. Before that version minified scripts and styles had extensions .js and .css, respectively; non-minified .dev.js and .dev.css. Now minified files have .min.js and .min.css extensions; non-minified — just .js and .css.

Notes

Changelog

Since 2.1.0 Introduced.
Since 6.3.0 The $in_footer parameter of type boolean was overloaded to be an $args parameter of type array.

wp_enqueue_script() code WP 6.5.2

function wp_enqueue_script( $handle, $src = '', $deps = array(), $ver = false, $args = array() ) {
	_wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );

	$wp_scripts = wp_scripts();

	if ( $src || ! empty( $args ) ) {
		$_handle = explode( '?', $handle );
		if ( ! is_array( $args ) ) {
			$args = array(
				'in_footer' => (bool) $args,
			);
		}

		if ( $src ) {
			$wp_scripts->add( $_handle[0], $src, $deps, $ver );
		}
		if ( ! empty( $args['in_footer'] ) ) {
			$wp_scripts->add_data( $_handle[0], 'group', 1 );
		}
		if ( ! empty( $args['strategy'] ) ) {
			$wp_scripts->add_data( $_handle[0], 'strategy', $args['strategy'] );
		}
	}

	$wp_scripts->enqueue( $handle );
}