wp_enqueue_script()WP 2.1.0

Correctly connects the script (JavaScript file) to the page.

Using this function to connect js files is important because it allows you to later combine JS files into one without unnecessary problems. Also, in some cases, you will avoid script conflicts when a dependent script is connected before the main one (the one it depends on).

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

IMPORTANT! This is a mistake made by beginner developers. The function will not output anything if wp_head() or wp_footer() is not used in the theme. It is at the moment of calling these functions that the hook is triggered, which adds the scripts.

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

If the script has already been registered using wp_register_script(), then to connect it in this function you only need to specify the script identifier (in the first parameter):

// jquery is registered in WP by default.
// Therefore, to connect it, one line is enough:
wp_enqueue_script('jquery');

If the script is not registered, it can be registered and connected at the same time:

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

Since version 3.3, wp_enqueue_script() can be called during page generation. In this case, the called script will be connected in the footer, at the moment the wp_footer event is triggered.

This function is typically called during the following events (hooks):

Returns

null. Returns nothing.

Usage template

//add_action( 'admin_enqueue_scripts', 'my_enqueue_scripts' );
//add_action( 'login_enqueue_scripts', 'my_enqueue_scripts' );
//add_action( 'enqueue_block_assets', 'my_enqueue_scripts' );
//add_action( 'enqueue_block_editor_assets', 'my_enqueue_scripts' );
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
function my_scripts_method(){
	wp_enqueue_script( 'newscript', get_template_directory_uri() . '/js/custom_script.js');
}

Usage

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

The name of the script (working title). A string 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 everything after will be added to the URL as query parameters. This allows you to specify the version of the connected script.

$src(string)

The URL of the script file. For example: http://example.com/wp-content/themes/my-theme/my-theme-script.js.

This parameter is only necessary when the script is not registered and WordPress does not yet know about this script, see the function wp_register_script().

You should not hardcode the URL; it should be determined dynamically. For this, use URL retrieval functions:

Links to external scripts can be specified without indicating the protocol: //otherdomain.com/js/their-script.js.

Already registered scripts in WP are listed below in this article.

Default: ''

$deps(array)
An array of script names that this script depends on; scripts that must be loaded before this script. This parameter is only necessary if WordPress does not yet know about this script.
Default: array()
$ver(string)

A string indicating the version of the script, if it has one. This parameter is used to ensure that the client receives the correct version of the script, not from the cache.

If the parameter is not specified, the version of the script will be the version of WordPress.

If you specify null, no version will be added.

Default: false

$args(array)

Parameters for connecting the script. Two parameters are supported:

  • in_footer(bool) - Default: false. Whether to output the script in the footer. By default, scripts are placed in the head section. If this parameter is true, the script will be output at the end of the body tag.

    If due to dependencies on other scripts it is not possible to connect the current script in the footer, then the value of this variable will be ignored and the script will be connected in the head.

    The function wp_footer() must be called in the theme before the closing </body> tag.

    Behaves the same as the previous (pre WP 6.3) implementation of the $in_footer parameter.

  • strategy(string) - Default: ''. Indicates how (by what strategy) the script should be loaded. Two values are available: defer and async for deferred and asynchronous scripts, respectively.

    By default, blocking behavior is used, which maintains backward compatibility with WP versions below 6.3.

Before WP 6.3, this parameter was called $in_footer and accepted true/false.
Starting from version 6.3, the parameter began to accept an array of data, and the previous parameter $in_footer was moved to the array element in_footer:

[
	'in_footer' => true,
	'strategy'  => 'async',
]

Read more about this change here.

Default: []

Examples

5

#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.

Scripts that come bundled with WP

WordPress registers many popular scripts by default (out of the box), i.e., such a script exists by default in WP. To add such a script to a page, you need to use its identifier in wp_enqueue_script( $id ).

The list is compiled from version WP 5.2.2

The current list can be viewed in the code of the function wp_default_scripts().

Name ID Dependency
  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.js 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

The list is obtained from the global variable $GLOBALS['wp_scripts']. Registered scripts may change depending on the page you are on. In the admin area, the list will be larger.

Changes

In version 3.5, WordPress changed its stance on minifying scripts and CSS styles. Previously, minified files had extensions: .js and .css respectively, while unminified ones had .dev.js and .dev.css. Now, minified files have the extension: .min.js and .min.css, while regular ones have .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.8.1

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 );
}