WordPress at a glance

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.

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:

If you want to enqueue the script on some condition, e.g. <!--[if lt IE 9]>...<![endif]-->, use wp_script_add_data()

No Hooks.

Return

Null. Nothing.

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

menu

Examples

#1 Replace the default script

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.

#2 Enqueue a default script

// For frontend of the site
add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); 
function my_scripts_method() {
	wp_enqueue_script( 'scriptaculous' );            
}

#3 Register and enqueue a custom script

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

#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'] );
}

#5 Enqueue a script that depends on a default script

Specify the name of the dependency in the third argument.

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

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

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

#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;
}
menu

jQuery in no-conflict mode

WordPress loads jQuery in «no conflict» mode by default. It was made for compatibility with other libraries that can be loaded as well.

In «no-confict» mode $ shortcut is not available. For example, this code will not work:

$(document).ready( function(){
	 $('#element') ...
});

You should tweak it a bit:

jQuery(document).ready( function($){
	$('#element') ...
});

Pay attention to the $ sign which is passed to the function - doing so we can use $ sign in the js code.

If you don't want to wait for "DOM ready" action, you can invoke function expression immediately:

(function($) {

	// Here $ refers to jQuery. So you can use $.

})(jQuery);

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.

menu

Notes

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

  • See: WP_Dependencies::add()
  • See: WP_Dependencies::add_data()
  • See: WP_Dependencies::enqueue()

Changelog

Since 2.1.0 Introduced.

Code of wp enqueue script: wp-includes/functions.wp-scripts.php WP 5.2.2

<?php
function wp_enqueue_script( $handle, $src = '', $deps = array(), $ver = false, $in_footer = false ) {
	$wp_scripts = wp_scripts();

	_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );

	if ( $src || $in_footer ) {
		$_handle = explode( '?', $handle );

		if ( $src ) {
			$wp_scripts->add( $_handle[0], $src, $deps, $ver );
		}

		if ( $in_footer ) {
			$wp_scripts->add_data( $_handle[0], 'group', 1 );
		}
	}

	$wp_scripts->enqueue( $handle );
}

Related Functions

From tag: script

More from category: Scripts and Styles

More from Template Tags: Main Functions

vladlu 100vlad.lu
Editors: kama 100
No comments
    Hello, !     Log In . Register