函数文档

wp_register_script()

💡 云策文档标注

概述

wp_register_script() 是 WordPress 中用于注册脚本的函数,以便后续通过 wp_enqueue_script() 加载。它允许定义脚本的依赖关系、版本控制和加载策略,简化代码管理并确保脚本按需加载。

关键要点

  • 注册脚本时需提供唯一句柄($handle)、脚本路径($src),可选参数包括依赖数组($deps)、版本号($ver)和额外参数($args)。
  • 从 WordPress 6.3 开始,$args 参数支持指定加载策略(如 'defer' 或 'async')和 fetchpriority,取代了之前的 $in_footer 布尔参数。
  • 注册的脚本如果被其他已加载脚本列为依赖,将自动加载,无需手动调用 wp_enqueue_script()。
  • 建议在适当的 action hook(如 wp_enqueue_scripts、admin_enqueue_scripts、login_enqueue_scripts 或 init)中调用此函数,以避免意外问题。
  • WordPress 核心已预注册了许多常用脚本(如 jquery、jquery-ui-core),开发者可直接依赖这些句柄而无需重新注册。

代码示例

wp_register_script(
    'foo',
    '/path/to/foo.js',
    array(),
    '1.0.0',
    array(
        'strategy' => 'defer',
    )
);

注意事项

  • 如果尝试用不同参数注册已存在的句柄,新参数将被忽略;需先使用 wp_deregister_script() 注销再重新注册。
  • jQuery UI Effects 不包含在 jquery-ui-core 句柄中,需单独处理。
  • 延迟加载策略(defer/async)会考虑依赖树,确保最终策略不会破坏依赖完整性。

📄 原文内容

Registers a new script.

Description

Registers a script to be enqueued later using the wp_enqueue_script() function.

See also

Parameters

$handlestringrequired
Name of the script. Should be unique.
$srcstring|falserequired
Full URL of the script, or path of the script relative to the WordPress root directory.
If source is set to false, script is an alias of other scripts it depends on.
$depsstring[]optional
An array of registered script handles this script depends on.

Default:array()

$verstring|bool|nulloptional
String specifying script version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version.
If set to null, no version is added.

Default:false

$argsarray|booloptional
An array of additional script loading strategies.
Otherwise, it may be a boolean in which case it determines whether the script is printed in the footer. Default false.

  • strategy string
    Optional. If provided, may be either 'defer' or 'async'.
  • in_footer bool
    Optional. Whether to print the script in the footer. Default 'false'.
  • fetchpriority string
    Optional. The fetch priority for the script. Default 'auto'.

Default:array()

Return

bool Whether the script has been registered. True on success, false on failure.

More Information

Scripts that have been pre-registered using wp_register_script() do not need to be manually enqueued using wp_enqueue_script() if they are listed as a dependency of another script that is enqueued. WordPress will automatically include the registered script before it includes the enqueued script that lists the registered script’s handle as a dependency.

Usage

wp_register_script( $handle, $src, $deps, $ver, $args );
  • Registering scripts is technically not necessary, but highly recommended nonetheless.
  • If the handle of a registered script is listed in the $deps array of dependencies of another script that is enqueued with wp_enqueue_script(), that script will be automatically loaded prior to loading the enqueued script. This greatly simplifies the process of ensuring that a script has all the dependencies it needs. See below for a simple example.
  • So, the main purpose of the register functions is to allow you to simplify your code by removing the need to duplicate code if you enqueue the same script or style in more than one section of code. The benefits of this are many and probably don’t need to be listed here.
  • As of WordPress 6.3, the new $args parameter – that replaces/overloads the prior $in_footer parameter – can be used to specify a script loading strategy. See the sections to follow for more information.

Notes

  • The function should be called using the wp_enqueue_scripts or init action hook if you want to call it on the front-end of the site. To call it on the administration screens, use the admin_enqueue_scripts action hook. For the login screen, use the login_enqueue_scripts action hook. Calling it outside of an action hook can often lead to unexpected results and should be avoided.
  • If attempt to register or enqueue an already registered handle with different parameters, the new parameters will be ignored. Instead, use wp_deregister_script() and register the script again with the new parameters.
  • jQuery UI Effects is not included with the jquery-ui-core handle

Delayed Script Loading

WordPress provides support for specifying a script loading strategy via the wp_register_script() and wp_enqueue_script() functions, by way of the strategy key within the new $args array parameter introduced in WordPress 6.3.

Supported strategies are as follows:

  • defer
    • Added by specifying an array key value pair of 'strategy' => 'defer' to the $args parameter.
    • Scripts marked for deferred execution — via the defer script attribute — are only executed once the DOM tree has fully loaded (but before the DOMContentLoaded and window load events). Deferred scripts are executed in the same order they were printed/added in the DOM, unlike asynchronous scripts.
  • async
    • Added by specifying an array key value pair of 'strategy' => 'async' to the $args parameter.
    • Scripts marked for asynchronous execution — via the async script attribute — are executed as soon as they are loaded by the browser. Asynchronous scripts do not have a guaranteed execution order, as script B (although added to the DOM after script A) may execute first given that it may complete loading prior to script A. Such scripts may execute either before the DOM has been fully constructed or after the DOMContentLoaded event.

Following is an example of specifying a loading strategy during script registration:

wp_register_script(
'foo',
'/path/to/foo.js',
array(),
'1.0.0',
array(
'strategy'  => 'defer',
)
);

The same approach applies when using

wp_enqueue_script()

.

When applying a loading strategy via either the wp_register_script() and wp_enqueue_script() functions, the scripts dependency tree is taken into consideration and the most eligible loading strategy is applied.

While the intended (delayed) strategy passed by the code author may not be the final one, it will never be a stricter one, thus maintaining the integrity of the dependency tree.

Core-Registered Scripts

By default, WordPress bundles many popular scripts commonly used by web developers besides the scripts used by core itself. Below is an (incomplete) list of the handles and paths of these scripts.

Handle Path in WordPress
utils /wp-includes/js/utils.js
common /wp-admin/js/common.js
sack /wp-includes/js/tw-sack.js
quicktags /wp-includes/js/quicktags.js
colorpicker /wp-includes/js/colorpicker.js
editor /wp-admin/js/editor.js
wp-fullscreen /wp-admin/js/wp-fullscreen.js
wp-ajax-response /wp-includes/js/wp-ajax-response.js
wp-pointer /wp-includes/js/wp-pointer.js
autosave /wp-includes/js/autosave.js
heartbeat /wp-includes/js/heartbeat.js
wp-auth-check /wp-includes/js/wp-auth-check.js
wp-lists /wp-includes/js/wp-lists.js
prototype external: //ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js
scriptaculous-root external: //ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js
scriptaculous-builder external: //ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/builder.js
scriptaculous-dragdrop external: //ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/dragdrop.js
scriptaculous-effects external: //ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/effects.js
scriptaculous-slider external: //ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/slider.js
scriptaculous-sound external: //ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/sound.js
scriptaculous-controls external: //ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/controls.js
scriptaculous scriptaculous-dragdrop, scriptaculous-slider, scriptaculous-controls
cropper /wp-includes/js/crop/cropper.js
jquery (v1.10.2 as of WP 3.8) jquery-core, jquery-migrate
jquery-core /wp-includes/js/jquery/jquery.js
jquery-migrate /wp-includes/js/jquery/jquery-migrate.js (v1.10.2 as of WP 3.8)
jquery-ui-core /wp-includes/js/jquery/ui/jquery.ui.core.min.js
jquery-effects-core /wp-includes/js/jquery/ui/jquery.ui.effect.min.js
jquery-effects-blind /wp-includes/js/jquery/ui/jquery.ui.effect-blind.min.js
jquery-effects-bounce /wp-includes/js/jquery/ui/jquery.ui.effect-bounce.min.js
jquery-effects-clip /wp-includes/js/jquery/ui/jquery.ui.effect-clip.min.js
jquery-effects-drop /wp-includes/js/jquery/ui/jquery.ui.effect-drop.min.js
jquery-effects-explode /wp-includes/js/jquery/ui/jquery.ui.effect-explode.min.js
jquery-effects-fade /wp-includes/js/jquery/ui/jquery.ui.effect-fade.min.js
jquery-effects-fold /wp-includes/js/jquery/ui/jquery.ui.effect-fold.min.js
jquery-effects-highlight /wp-includes/js/jquery/ui/jquery.ui.effect-highlight.min.js
jquery-effects-pulsate /wp-includes/js/jquery/ui/jquery.ui.effect-pulsate.min.js
jquery-effects-scale /wp-includes/js/jquery/ui/jquery.ui.effect-scale.min.js
jquery-effects-shake /wp-includes/js/jquery/ui/jquery.ui.effect-shake.min.js
jquery-effects-slide /wp-includes/js/jquery/ui/jquery.ui.effect-slide.min.js
jquery-effects-transfer /wp-includes/js/jquery/ui/jquery.ui.effect-transfer.min.js
jquery-ui-accordion /wp-includes/js/jquery/ui/jquery.ui.accordion.min.js
jquery-ui-autocomplete /wp-includes/js/jquery/ui/jquery.ui.autocomplete.min.js
jquery-ui-button /wp-includes/js/jquery/ui/jquery.ui.button.min.js
jquery-ui-datepicker /wp-includes/js/jquery/ui/jquery.ui.datepicker.min.js
jquery-ui-dialog /wp-includes/js/jquery/ui/jquery.ui.dialog.min.js
jquery-ui-draggable /wp-includes/js/jquery/ui/jquery.ui.draggable.min.js
jquery-ui-droppable /wp-includes/js/jquery/ui/jquery.ui.droppable.min.js
jquery-ui-menu /wp-includes/js/jquery/ui/jquery.ui.menu.min.js
jquery-ui-mouse /wp-includes/js/jquery/ui/jquery.ui.mouse.min.js
jquery-ui-position /wp-includes/js/jquery/ui/jquery.ui.position.min.js
jquery-ui-progressbar /wp-includes/js/jquery/ui/jquery.ui.progressbar.min.js
jquery-ui-resizable /wp-includes/js/jquery/ui/jquery.ui.resizable.min.js
jquery-ui-selectable /wp-includes/js/jquery/ui/jquery.ui.selectable.min.js
jquery-ui-slider /wp-includes/js/jquery/ui/jquery.ui.slider.min.js
jquery-ui-sortable /wp-includes/js/jquery/ui/jquery.ui.sortable.min.js
jquery-ui-spinner /wp-includes/js/jquery/ui/jquery.ui.spinner.min.js
jquery-ui-tabs /wp-includes/js/jquery/ui/jquery.ui.tabs.min.js
jquery-ui-tooltip /wp-includes/js/jquery/ui/jquery.ui.tooltip.min.js
jquery-ui-widget /wp-includes/js/jquery/ui/jquery.ui.widget.min.js
jquery-form /wp-includes/js/jquery/jquery.form.js
jquery-color /wp-includes/js/jquery/jquery.color.min.js
suggest /wp-includes/js/jquery/suggest.js
schedule /wp-includes/js/jquery/jquery.schedule.js
jquery-query /wp-includes/js/jquery/jquery.query.js
jquery-serialize-object /wp-includes/js/jquery/jquery.serialize-object.js
jquery-hotkeys /wp-includes/js/jquery/jquery.hotkeys.js
jquery-table-hotkeys /wp-includes/js/jquery/jquery.table-hotkeys.js
jquery-touch-punch /wp-includes/js/jquery/jquery.ui.touch-punch.js
jquery-masonry /wp-includes/js/jquery/jquery.masonry.min.js
thickbox /wp-includes/js/thickbox/thickbox.js
jcrop /wp-includes/js/jcrop/jquery.Jcrop.js
swfobject /wp-includes/js/swfobject.js
plupload /wp-includes/js/plupload/plupload.js
plupload-html5 wp-includes/js/plupload/plupload.html5.js
plupload-flash /wp-includes/js/plupload/plupload.flash.js
plupload-silverlight /wp-includes/js/plupload/plupload.silverlight.js
plupload-html4 /wp-includes/js/plupload/plupload.html4.js
plupload-all plupload, plupload-html5, plupload-flash, plupload-silverlight, plupload-html4
plupload-handlers /wp-includes/js/plupload/handlers.js
wp-plupload /wp-includes/js/plupload/wp-plupload.js
swfupload /wp-includes/js/swfupload/swfupload.js
swfupload-swfobject /wp-includes/js/swfupload/plugins/swfupload.swfobject.js
swfupload-queue /wp-includes/js/swfupload/plugins/swfupload.queue.js
swfupload-speed /wp-includes/js/swfupload/plugins/swfupload.speed.js
swfupload-all /wp-includes/js/swfupload/swfupload-all.js
swfupload-handlers /wp-includes/js/swfupload/handlers.js
comment-reply /wp-includes/js/comment-reply.js
json2 /wp-includes/js/json2.js
underscore /wp-includes/js/underscore.min.js
backbone /wp-includes/js/backbone.min.js
wp-util /wp-includes/js/wp-util.js
wp-backbone /wp-includes/js/wp-backbone.js
revisions /wp-admin/js/revisions.js
imgareaselect /wp-includes/js/imgareaselect/jquery.imgareaselect.js
mediaelement /wp-includes/js/mediaelement/mediaelement-and-player.min.js
wp-mediaelement /wp-includes/js/mediaelement/wp-mediaelement.js
zxcvbn-async /wp-includes/js/zxcvbn-async.js
password-strength-meter /wp-admin/js/password-strength-meter.js
user-profile /wp-admin/js/user-profile.js
user-suggest /wp-admin/js/user-suggest.js
admin-bar /wp-includes/js/admin-bar.js
wplink /wp-includes/js/wplink.js
wpdialogs /wp-includes/js/tinymce/plugins/wpdialogs/js/wpdialog.js
wpdialogs-popup /wp-includes/js/tinymce/plugins/wpdialogs/js/popup.js
word-count /wp-admin/js/word-count.js
media-upload /wp-admin/js/media-upload.js
hoverIntent /wp-includes/js/hoverIntent.js
customize-base /wp-includes/js/customize-base.js
customize-loader
customize-preview
customize-controls
accordion
shortcode
media-models
media-views
media-editor
mce-view
admin-tags
admin-comments
xfn
postbox
post
link
comment
admin-gallery
admin-widgets
theme
theme-install
inline-edit-post
inline-edit-tax
plugin-install
farbtastic
iris
wp-color-picker
dashboard
list-revisions
media
image-edit
set-post-thumbnail
nav-menu
custom-header
custom-background
media-gallery
svg-painter

Source

function wp_register_script( $handle, $src, $deps = array(), $ver = false, $args = array() ) {
	if ( ! is_array( $args ) ) {
		$args = array(
			'in_footer' => (bool) $args,
		);
	}
	_wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );

	$wp_scripts = wp_scripts();

	$registered = $wp_scripts->add( $handle, $src, $deps, $ver );
	if ( ! empty( $args['in_footer'] ) ) {
		$wp_scripts->add_data( $handle, 'group', 1 );
	}
	if ( ! empty( $args['strategy'] ) ) {
		$wp_scripts->add_data( $handle, 'strategy', $args['strategy'] );
	}
	if ( ! empty( $args['fetchpriority'] ) ) {
		$wp_scripts->add_data( $handle, 'fetchpriority', $args['fetchpriority'] );
	}
	return $registered;
}

Changelog

Version Description
6.9.0 The $fetchpriority parameter of type string was added to the $args parameter of type array.
6.3.0 The $in_footer parameter of type boolean was overloaded to be an $args parameter of type array.
4.3.0 A return value was added.
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 8 content

    Corrected code from Luizaris:

    add_action("wp_enqueue_scripts", "myscripts");
    function myscripts() { 
        wp_register_script('myfirstscript', 
                            get_template_directory_uri() .'/myscript.js',   //
                            array ('jquery', 'jquery-ui'),					//depends on these, however, they are registered by core already, so no need to enqueue them.
                            false, false);
        wp_enqueue_script('myfirstscript');
         
    }

  2. Skip to note 9 content

    Note to moderator: if there’s a better place to report this feedback, please email me at josh@cnpagency.com. I checked WordPress Trac, but it didn’t seem to be the right place for documentation feedback.

    I disagree with this part of the documentation:

    The function should be called using the wp_enqueue_scripts action hook if you want to call it on the front-end of the site. To call it on the administration screens, use the admin_enqueue_scripts action hook. For the login screen, use the login_enqueue_scripts action hook. Calling it outside of an action hook can often lead to unexpected results and should be avoided.

    First off, according to _wp_scripts_maybe_doing_it_wrong, init is also an acceptable hook for registering scripts. The benefit we get from registering scripts on init is that plugins can get a comprehensive list of the registered scripts and styles in the WordPress Admin by accessing the “registered” property of the $wp_scripts and $wp_styles globals. If we’re going to register scripts and styles, we should be able to pull a full list of the registered scripts and styles. The recommended usage is only for code efficiency, and has no other useful aspect to it.

  3. Skip to note 10 content

    In a case where first script should be loaded only if another second script is loaded:

    function my_enqueue_scripts()
    {
        wp_register_script( 'first', get_template_directory_uri() . 'js/first.js' );
    
        wp_enqueue_script( 'second', get_template_directory_uri() . 'js/second.js', array( 'first' ) );
    }
    add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );

    Here, first.js will load( before second.js ) only if second.js is enqueued/loaded.

  4. Skip to note 11 content

    Clearing confusion between all three functions. wp_enqueue_script() , wp_register_script() , and wp_localize_script()

    wp_register_script()::
    Registers a script with WordPress.
    Does not load the script on the page.
    Useful when you want to define a script for later use with specific conditions or dependencies.
    Takes arguments like script handle (unique identifier), script path (URL or relative path to the file), and optional arguments like version number and dependencies on other scripts.

    wp_enqueue_script()::
    Enqueues a script that need to be loaded on the page.
    Can also register the script if it hasn’t been registered before.
    Useful for including scripts you need on a specific page or based on certain conditions (e.g., only on the front-end).
    Takes arguments like script handle (same as used with wp_register_script) and optional arguments like version number, dependencies, and placement (in the header or footer).
    Here’s a key difference:

    wp_enqueue_script can handle both registering and loading a script in one call.
    wp_register_script only registers the script for later use with wp_enqueue_script or another function that might need it.

    wp_localize_script()::
    Does not register or enqueue a script.
    Used to localize a registered script, meaning it injects PHP variables into the script as JavaScript objects.
    Useful for passing data from WordPress (PHP) to your JavaScript code.
    Takes arguments like script handle (of an already registered script), a variable name to hold the data in JavaScript, and the actual PHP data (array or object) you want to pass.

    In short,
    Use wp_register_script to define scripts for later use.
    Use wp_enqueue_script to load scripts on the page (can also register if needed).
    Use wp_localize_script to pass data from PHP to your registered JavaScript code.

  5. Skip to note 12 content

    Using register_script() to add a script and its dependencies

    function myscripts() {
        //get some external script that is needed for this script
        wp_enqueue_script('jquery-ui', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js'); 
        $script = get_template_directory_uri() . '/library/myscript.js';
        wp_register_script('myfirstscript', 
                            $script, 
                            array ('jquery', 'jquery-ui'), 
                            false, false);
        //always enqueue the script after registering or nothing will happen
        wp_enqueue_script('fullpage-slimscroll');
        
    }
    add_action("wp_enqueue_scripts", "myscripts");