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

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

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 scripts:

Script Name ID Dependency
Image Cropper Image cropper (not used in core, see jcrop)
Jcrop jcrop
SWFObject swfobject
SWFUpload swfupload
SWFUpload Degrade swfupload-degrade
SWFUpload Queue swfupload-queue
SWFUpload Handlers swfupload-handlers
     
jQuery jquery json2 (for AJAX calls)
jQuery Form jquery-form jquery
jQuery Color jquery-color jquery
jQuery Masonry jquery-masonry jquery
Masonry (native Javascript) masonry
jQuery UI Core jquery-ui-core jquery
jQuery UI Widget jquery-ui-widget jquery
jQuery UI Accordion jquery-ui-accordion jquery
jQuery UI Autocomplete jquery-ui-autocomplete jquery
jQuery UI Button jquery-ui-button jquery
jQuery UI Datepicker jquery-ui-datepicker jquery
jQuery UI Dialog jquery-ui-dialog jquery
jQuery UI Draggable jquery-ui-draggable jquery
jQuery UI Droppable jquery-ui-droppable jquery
jQuery UI Menu jquery-ui-menu jquery
jQuery UI Mouse jquery-ui-mouse jquery
jQuery UI Position jquery-ui-position jquery
jQuery UI Progressbar jquery-ui-progressbar jquery
jQuery UI Selectable jquery-ui-selectable jquery
jQuery UI Resizable jquery-ui-resizable jquery
jQuery UI Selectmenu jquery-ui-selectmenu jquery
jQuery UI Sortable jquery-ui-sortable jquery
jQuery UI Slider jquery-ui-slider jquery
jQuery UI Spinner jquery-ui-spinner jquery
jQuery UI Tooltips jquery-ui-tooltip jquery
jQuery UI Tabs jquery-ui-tabs 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 UI Effects - Pulsate jquery-effects-pulsate jquery-effects-core
jQuery UI Effects - Scale jquery-effects-scale jquery-effects-core
jQuery UI Effects - Shake jquery-effects-shake jquery-effects-core
jQuery UI Effects - Slide jquery-effects-slide jquery-effects-core
jQuery UI Effects - Transfer jquery-effects-transfer jquery-effects-core
MediaElement.js (WP 3.6+) wp-mediaelement jquery
jQuery Schedule schedule jquery
jQuery Suggest suggest jquery
     
ThickBox thickbox
jQuery HoverIntent hoverIntent jquery
jQuery Hotkeys jquery-hotkeys jquery
Simple AJAX Code-Kit sack
QuickTags quicktags
Iris (Colour picker) iris jquery
Farbtastic (deprecated) farbtastic jquery
ColorPicker (deprecated) colorpicker jquery
Tiny MCE tiny_mce
Heartbeat heartbeat jquery
Autosave autosave
WordPress AJAX Response wp-ajax-response
List Manipulation wp-lists
WP Common common
WP Editor editorremov
WP Editor Functions editor-functions
AJAX Cat ajaxcat
Admin Categories admin-categories
Admin Tags admin-tags
Admin custom fields admin-custom-fields
Password Strength Meter password-strength-meter
Admin Comments admin-comments
Admin Users admin-users
Admin Forms admin-forms
XFN xfn
Upload upload
PostBox postbox
Slug slug
Post post
Page page
Link link
Comment comment
Threaded Comments comment-reply
Admin Gallery admin-gallery
Media Upload media-upload
Admin widgets admin-widgets
Word Count word-count
Theme Preview theme-preview
JSON for JS json2
Plupload Core plupload
Plupload All Runtimes plupload-all
Plupload HTML4 plupload-html4
Plupload HTML5 plupload-html5
Plupload Flash plupload-flash
Plupload Silverlight plupload-silverlight
Underscore js underscore
Backbone js backbone

This is not a full list. To get full list, see the global variable $GLOBALS['wp_scripts'] in the admin.

Or see code of wp_default_scripts() function. This function registers all default scripts.

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.

Code of wp enqueue script: wp-includes/functions.wp-scripts.php VER 5.1.1

<?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 100
Editors: kama 100
No comments
    Hello, !     Log In . Register