WordPress.org

Ready to get started?Download WordPress

Codex

zh-cn:函数参考/wp enqueue script

旧的翻译
本文已被标记为未完成状态。您可以将其补充或翻译完整,以此帮助完善 Codex。

Contents

说明

使用 wp_enqueue_script() 可以安全地将 javascript 脚本加入到 WordPress 创建的页面中。一般来说,将没有被内置的代码进行添加,并在 WordPress 运行时进行加载。

The safe and recommended method of adding JavaScript to a WordPress generated page is by using wp_enqueue_script(). This function includes the script if it hasn't already been included, and safely handles dependencies.

用法

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

使用 wp_enqueue_scripts 行为来调用本功能, 或使用 admin_enqueue_scripts 在管理界面进行调用, 或使用 login_enqueue_scripts 在登陆后调用. 在行为之外进行调用将会导致问题产生。参见#11526获得详细信息。

Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side, or use login_enqueue_scripts for login screens.

参数

$handle
(string) (required) 脚本的名称,使用小写字母.
Default: None
$src
(string) (optional) 脚本url路径. 例: "http://example.com/wp-includes/js/scriptaculous/scriptaculous.js". 这个参数只在wordpress还没有加载该脚本的时候需要This parameter is only required when WordPress does not already know about this script. You should never hardcode URLs to local scripts, use plugins_url() (for Plugins) and get_template_directory_uri() (for Themes) to get a proper URL.
Default: false
$deps
(array) (optional) Array of handles of any script that this script depends on (scripts that must be loaded before this script). false if there are no dependencies. This parameter is only required when WordPress does not already know about this script.
Default: array()
$ver
(string) (optional) String specifying the script version number, if it has one, which is concatenated to the end of the path as a query string. Defaults to false. If no version is specified or set to false then WordPress automatically adds a version number equal to the current version of WordPress you are running. If set to null no version is added. This parameter is used to ensure that the correct version is sent to the client regardless of caching, and so should be included if a version number is available and makes sense for the script.
Default: false
$in_footer
(boolean) (optional) Normally scripts are placed in the <head> section. If this parameter is true the script is placed at the bottom of the <body>. This requires the theme to have the wp_footer() hook in the appropriate place. Note that you have to enqueue your script before wp_head is run, even if it will be placed in the footer.
Default: false

返回值

(void) 
本函数不返回任何值。

举例

注意: This function will not work if it is called from a wp_head or wp_print_scripts actions, as the files need to be enqueued before those actions are run. See the Usage section for the correct hooks to use.


从一个非缺省的路径中加载一个缺省的wordpress脚本

请注意: It is not recommended that a theme force a 3rd party served JavaScript or CSS file by default, Doing so opens the users up to reliance upon a external host which is out of their control. A much better alternative is to use/recomend a Plugin such as Plugin: Use Google Libraries which automatically uses the Google-CDN served jQuery of the same version that WordPress uses this ultimately reduces breakage caused by Themes/Plugins which hardcode the file to use.

WARNING: Plugins that use this method to off-load any scripts that are built in to WordPress will be rejected.

Suppose you want to use the CDN copy of jQuery instead of WordPress’s, add this code to your functions.php file.

<?php
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' );
}    
 
add_action('wp_enqueue_scripts', 'my_scripts_method');
?>

by using the wp_enqueue_scripts hook (instead of the init hook which many articles reference), we avoid registering the alternate jQuery on admin pages, which will cause post editing (amongst other things) to break after upgrades often.

Load the scriptaculous script

<?php
function my_scripts_method() {
    wp_enqueue_script('scriptaculous');            
}    
 
add_action('wp_enqueue_scripts', 'my_scripts_method'); // For use on the Front end (ie. Theme)
?>

The above example only loads the Scriptaculous library on the front end, If it was needed within the admin, you could use the admin_enqueue_scripts action instead, however this enqueues it on ALL admin pages, which often leads to plugin/core conflicts, ultimately breaking the WordPress admin experience. Instead, You should only load it on the individual pages you need it, See the Load scripts only on Plugin pages section for an example of that.

Load a script that depends on scriptaculous

Add and load a new script that depends on Scriptaculous. This will cause WordPress to load Scriptaculous into the page before the new script.

<?php
function my_scripts_method() {
	wp_enqueue_script(
		'newscript',
		plugins_url('/js/newscript.js', __FILE__),
		array('scriptaculous')
	);
}    
 
add_action('wp_enqueue_scripts', 'my_scripts_method');
?>

加载你的主题中基于wordpress脚本的脚本

Often JavaScript files included in Themes require another JavaScript file to be loaded before the theme's JavaScript file. WordPress offers an API for marking dependencies when registering a script. For example, the below theme requires jQuery for the custom_script JavaScript file:

<?php
function my_scripts_method() {
	wp_enqueue_script(
		'custom-script',
		get_template_directory_uri() . '/js/custom_script.js',
		array('jquery')
	);
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
?>

Load scripts only on plugin pages

<?php
    add_action( 'admin_init', 'my_plugin_admin_init' );
    add_action( 'admin_menu', 'my_plugin_admin_menu' );

    function my_plugin_admin_init() {
        /* Register our script. */
        wp_register_script( 'my-plugin-script', plugins_url('/script.js', __FILE__) );
    }

    function my_plugin_admin_menu() {
        /* Register our plugin page */
        $page = add_submenu_page( 'edit.php', // The parent page of this menu
                                  __( 'My Plugin', 'myPlugin' ), // The Menu Title
                                  __( 'My Plugin', 'myPlugin' ), // The Page title
				  'manage_options', // The capability required for access to this item
				  'my_plugin-options', // the slug to use for the page in the URL
                                  'my_plugin_manage_menu' // The function to call to render the page
                               );

        /* Using registered $page handle to hook script load */
        add_action('admin_print_scripts-' . $page, 'my_plugin_admin_scripts');
    }

    function my_plugin_admin_scripts() {
        /*
         * It will be called only on your plugin admin page, enqueue our script here
         */
        wp_enqueue_script( 'my-plugin-script' );
    }

    function my_plugin_manage_menu() {
        /* Output our admin page */
    }
?>

jQuery noConflict wrappers

Note: The jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load.

In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used. For example:

$(document).ready(function(){
     $(#somefunction) ...
});

Becomes:

jQuery(document).ready(function(){
    jQuery(#somefunction) ...
});

In order to use the default jQuery shortcut of $, you can use the following wrapper around your code:

jQuery(document).ready(function($) {
    // $() will work as an alias for jQuery() inside of this function
});

That wrapper will cause your code to be executed when the page finishes loading, and the $ will work for calling jQuery. If, for some reason, you want your code to execute immediately (instead of waiting for the DOM ready event), then you can use this wrapper method instead:

(function($) {
    // $() will work as an alias for jQuery() inside of this function
})(jQuery);

Default scripts included with WordPress

Script Name Handle Needed Dependency *
Image Cropper Image cropper (not used in core, see jcrop)
Jcrop Image copper
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 UI Core jquery-ui-core (Att.: This is not the whole core incl. all core plugins. Just the base core.) jquery
jQuery UI Widget jquery-ui-widget jquery
jQuery UI Mouse jquery-ui-mouse jquery
jQuery UI Accordion jquery-ui-accordion jquery
jQuery UI Autocomplete jquery-ui-autocomplete jquery
jQuery UI Slider jquery-ui-slider jquery
jQuery UI Tabs jquery-ui-tabs jquery
jQuery UI Sortable jquery-ui-sortable jquery
jQuery UI Draggable jquery-ui-draggable jquery
jQuery UI Droppable jquery-ui-droppable jquery
jQuery UI Selectable jquery-ui-selectable jquery
jQuery UI Datepicker jquery-ui-datepicker jquery
jQuery UI Resizable jquery-ui-resizable jquery
jQuery UI Dialog jquery-ui-dialog jquery
jQuery UI Button jquery-ui-button jquery
jQuery Schedule schedule jquery
jQuery Suggest suggest jquery
ThickBox thickbox
jQuery Hotkeys jquery-hotkeys jquery
Simple AJAX Code-Kit sack
QuickTags quicktags
Farbtastic (color picker) farbtastic jquery
ColorPicker (deprecated) colorpicker jquery
Tiny MCE tiny_mce
Autosave autosave
WordPress AJAX Response wp-ajax-response
List Manipulation wp-lists
WP Common common
WP Editor editor
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 plupload


Removed from Core
Script Name Handle Removed Version Replaced With
Scriptaculous Root scriptaculous-root WP 3.5 Google Version
Scriptaculous Builder scriptaculous-builder WP 3.5 Google Version
Scriptaculous Drag & Drop scriptaculous-dragdrop WP 3.5 Google Version
Scriptaculous Effects scriptaculous-effects WP 3.5 Google Version
Scriptaculous Slider scriptaculous-slider WP 3.5 Google Version
Scriptaculous Sound scriptaculous-sound WP 3.5 Google Version
Scriptaculous Controls scriptaculous-controls WP 3.5 Google Version
Scriptaculous scriptaculous WP 3.5 Google Version
Prototype Framework prototype WP 3.5 Google Version

For a detailed list of names that can be used as $handle, see Notes on wp_register_script();.

The list is far from complete. For more details (a complete list of registered files) inspect the $GLOBALS['wp_scripts'] in the admin UI. Registered scripts might change per requested page.

* Dependencies not complete.

Notes

  • See WP_Scripts::add_data(), WP_Scripts::enqueue()
  • Uses global: (unknown type) $wp_scripts
  • jQuery UI Effects is NOT included with the jquery-ui-core
  • As of WordPress 3.3 wp_enqueue_script() can be called mid-page (in the HTML body). This will load the script in the footer.

Change Log

Since: 2.6 (BackPress version: r16)

Source File

wp_enqueue_script() is located in wp-includes/functions.wp-scripts.php.

Resources

Related

See also index of Function Reference and index of Template Tags.
This article is marked as in need of editing. You can help Codex by editing it.