返回介绍

wp_enqueue_script()

发布于 2017-09-11 11:55:54 字数 27107 浏览 938 评论 0 收藏 0

wp_enqueue_script( string $handle,  string $src = '',  array $deps = array(),  string|bool|null $ver = false,  bool $in_footer = false )

Enqueue a script.


description

Registers the script if $src provided (does NOT overwrite), and enqueues it.


参数

$handle

(string) (Required) Name of the script. Should be unique.

$src

(string) (Optional) Full URL of the script, or path of the script relative to the WordPress root directory.

Default value: ''

$deps

(array) (Optional) An array of registered script handles this script depends on.

Default value: array()

$ver

(string|bool|null) (Optional) 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 value: false

$in_footer

(bool) (Optional) Whether to enqueue the script before </body> instead of in the <head>. Default 'false'.

Default value: false


源代码

File: wp-includes/functions.wp-scripts.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 );
}

更新日志

Versiondescription
2.1.0Introduced.

More Information

Usage


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

Links a script file to the generated page at the right time according to the script dependencies, if the script has not been already included and if all the dependencies have been registered. You could either link a script with a handle previously registered using the wp_register_script() function, or provide this function with all the parameters necessary to link a script.

This is the recommended method of linking JavaScript to a WordPress generated page.

Notes

  • 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, like in the examples above. 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 lead to problems, see the ticket
  • If you try 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.
  • This function relies on the use of wp_head() and wp_footer() by the active theme. This means that it may not work with a few very old themes that do not call these functions. This is useful to keep in mind when debugging ancient themes.
  • Uses: WP_Scripts::add(), WP_Scripts::add_data() and WP_Scripts::enqueue().
  • Uses global: (unknown type) $wp_scripts.

Default Scripts Included and Registered by WordPress

By default, WordPress installation includes many popular scripts commonly used by web developers besides the scripts used by WordPress itself. Some of them are listed in the table below.

For a detailed list of names that can be used in place of the $handle parameter, see wp_register_script().

Script NameHandleNeeded Dependency *
Image CropperImage cropper (not used in core, see jcrop)
Jcropjcrop
SWFObjectswfobject
SWFUploadswfupload
SWFUpload Degradeswfupload-degrade
SWFUpload Queueswfupload-queue
SWFUpload Handlersswfupload-handlers
jQueryjqueryjson2 (for AJAX calls)
jQuery Formjquery-formjquery
jQuery Colorjquery-colorjquery
jQuery Masonryjquery-masonryjquery
Masonry (native Javascript)masonryimagesloaded
jQuery UI Corejquery-ui-corejquery
jQuery UI Widgetjquery-ui-widgetjquery
jQuery UI Accordionjquery-ui-accordionjquery
jQuery UI Autocompletejquery-ui-autocompletejquery
jQuery UI Buttonjquery-ui-buttonjquery
jQuery UI Datepickerjquery-ui-datepickerjquery
jQuery UI Dialogjquery-ui-dialogjquery
jQuery UI Draggablejquery-ui-draggablejquery
jQuery UI Droppablejquery-ui-droppablejquery
jQuery UI Menujquery-ui-menujquery
jQuery UI Mousejquery-ui-mousejquery
jQuery UI Positionjquery-ui-positionjquery
jQuery UI Progressbarjquery-ui-progressbarjquery
jQuery UI Selectablejquery-ui-selectablejquery
jQuery UI Resizablejquery-ui-resizablejquery
jQuery UI Selectmenujquery-ui-selectmenujquery
jQuery UI Sortablejquery-ui-sortablejquery
jQuery UI Sliderjquery-ui-sliderjquery
jQuery UI Spinnerjquery-ui-spinnerjquery
jQuery UI Tooltipsjquery-ui-tooltipjquery
jQuery UI Tabsjquery-ui-tabsjquery
jQuery UI Effectsjquery-effects-corejquery
jQuery UI Effects – Blindjquery-effects-blindjquery-effects-core
jQuery UI Effects – Bouncejquery-effects-bouncejquery-effects-core
jQuery UI Effects – Clipjquery-effects-clipjquery-effects-core
jQuery UI Effects – Dropjquery-effects-dropjquery-effects-core
jQuery UI Effects – Explodejquery-effects-explodejquery-effects-core
jQuery UI Effects – Fadejquery-effects-fadejquery-effects-core
jQuery UI Effects – Foldjquery-effects-foldjquery-effects-core
jQuery UI Effects – Highlightjquery-effects-highlightjquery-effects-core
jQuery UI Effects – Pulsatejquery-effects-pulsatejquery-effects-core
jQuery UI Effects – Scalejquery-effects-scalejquery-effects-core
jQuery UI Effects – Shakejquery-effects-shakejquery-effects-core
jQuery UI Effects – Slidejquery-effects-slidejquery-effects-core
jQuery UI Effects – Transferjquery-effects-transferjquery-effects-core
MediaElement.js (WP 3.6+)wp-mediaelementjquery
jQuery Scheduleschedulejquery
jQuery Suggestsuggestjquery
ThickBoxthickbox
jQuery HoverIntenthoverIntentjquery
jQuery Hotkeysjquery-hotkeysjquery
Simple AJAX Code-Kitsack
QuickTagsquicktags
Iris (Colour picker)irisjquery
Farbtastic (deprecated)farbtasticjquery
ColorPicker (deprecated)colorpickerjquery
Tiny MCEtiny_mce
Autosaveautosave
WordPress AJAX Responsewp-ajax-response
List Manipulationwp-lists
WP Commoncommon
WP Editoreditorremov
WP Editor Functionseditor-functions
AJAX Catajaxcat
Admin Categoriesadmin-categories
Admin Tagsadmin-tags
Admin custom fieldsadmin-custom-fields
Password Strength Meterpassword-strength-meter
Admin Commentsadmin-comments
Admin Usersadmin-users
Admin Formsadmin-forms
XFNxfn
Uploadupload
PostBoxpostbox
Slugslug
Postpost
Pagepage
Linklink
Commentcomment
Threaded Commentscomment-reply
Admin Galleryadmin-gallery
Media Uploadmedia-upload
Admin widgetsadmin-widgets
Word Countword-count
Theme Previewtheme-preview
JSON for JSjson2
Plupload Coreplupload
Plupload All Runtimesplupload-all
Plupload HTML4plupload-html4
Plupload HTML5plupload-html5
Plupload Flashplupload-flash
Plupload Silverlightplupload-silverlight
Underscore jsunderscore
Backbone jsbackbone
imagesLoadedimagesloaded
Removed from Core
Script NameHandleRemoved VersionReplaced With
Scriptaculous Rootscriptaculous-rootWP 3.5Google Version
Scriptaculous Builderscriptaculous-builderWP 3.5Google Version
Scriptaculous Drag & Dropscriptaculous-dragdropWP 3.5Google Version
Scriptaculous Effectsscriptaculous-effectsWP 3.5Google Version
Scriptaculous Sliderscriptaculous-sliderWP 3.5Google Version
Scriptaculous Soundscriptaculous-soundWP 3.5Google Version
Scriptaculous Controlsscriptaculous-controlsWP 3.5Google Version
ScriptaculousscriptaculousWP 3.5Google Version
Prototype FrameworkprototypeWP 3.5Google Version

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


* The listed dependencies are not complete.


相关函数

Uses

  • wp-includes/functions.wp-scripts.php: wp_scripts()

Used By

  • wp-includes/widgets/class-wp-widget-text.php: WP_Widget_Text::enqueue_admin_scripts()
  • wp-includes/widgets/class-wp-widget-media-audio.php: WP_Widget_Media_Audio::enqueue_admin_scripts()
  • wp-includes/widgets/class-wp-widget-media-video.php: WP_Widget_Media_Video::enqueue_preview_scripts()
  • wp-includes/widgets/class-wp-widget-media-video.php: WP_Widget_Media_Video::enqueue_admin_scripts()
  • wp-includes/widgets/class-wp-widget-media-audio.php: WP_Widget_Media_Audio::enqueue_preview_scripts()
  • wp-includes/widgets/class-wp-widget-media.php: WP_Widget_Media::enqueue_admin_scripts()
  • wp-includes/widgets/class-wp-widget-media-image.php: WP_Widget_Media_Image::enqueue_admin_scripts()
  • wp-includes/theme.php: the_custom_header_markup()
  • wp-includes/customize/class-wp-customize-selective-refresh.php: WP_Customize_Selective_Refresh::enqueue_preview_scripts()
  • wp-includes/embed.php: wp_oembed_add_host_js()
  • wp-includes/customize/class-wp-customize-cropped-image-control.php: WP_Customize_Cropped_Image_Control::enqueue()
  • wp-includes/class-wp-customize-nav-menus.php: WP_Customize_Nav_Menus::customize_preview_enqueue_deps()
  • wp-includes/class-wp-customize-nav-menus.php: WP_Customize_Nav_Menus::enqueue_scripts()
  • wp-admin/includes/class-wp-press-this.php: WP_Press_This::html()
  • wp-admin/includes/class-wp-internal-pointers.php: WP_Internal_Pointers::enqueue_scripts()
  • wp-admin/includes/template.php: do_accordion_sections()
  • wp-admin/includes/media.php: wp_media_upload_handler()
  • wp-admin/includes/media.php: media_upload_gallery()
  • wp-admin/includes/comment.php: enqueue_comment_hotkeys_js()
  • wp-admin/custom-header.php: Custom_Image_Header::js_includes()
  • wp-admin/custom-background.php: Custom_Background::admin_load()
  • wp-includes/class-wp-customize-manager.php: WP_Customize_Manager::customize_preview_init()
  • wp-includes/general-template.php: add_thickbox()
  • wp-includes/functions.php: wp_auth_check_load()
  • wp-includes/class-wp-admin-bar.php: WP_Admin_Bar::initialize()
  • wp-includes/media.php: wp_enqueue_media()
  • wp-includes/media.php: wp_video_shortcode()
  • wp-includes/media.php: wp_playlist_scripts()
  • wp-includes/media.php: wp_audio_shortcode()
  • wp-includes/customize/class-wp-customize-header-image-control.php: WP_Customize_Header_Image_Control::enqueue()
  • wp-includes/customize/class-wp-customize-color-control.php: WP_Customize_Color_Control::enqueue()
  • wp-includes/class-wp-customize-widgets.php: WP_Customize_Widgets::enqueue_scripts()
  • wp-includes/class-wp-customize-widgets.php: WP_Customize_Widgets::customize_preview_enqueue()
  • wp-includes/class-wp-editor.php: _WP_Editors::enqueue_scripts()
  • Show 29 more used by Hide more used by

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 20You must log in to vote on the helpfulness of this note Contributed by bcworkz

    When you enqueue script that is dependent on jQuery, note that the jQuery in WordPress runs in noConflict mode, which means you cannot use the common $ alias. You must use the full jQuery instead. Alternately, place your code using the $ shortcut inside a noConflict wrapper.

    
    jQuery( document ).ready( function( $ ) {
        // $() will work as an alias for jQuery() inside of this function
        [ your code goes here ]
    } );
  2. Using a Hook

    Enqueue both scripts and styles from a single action hook.

    
    /**
     * Proper way to enqueue scripts and styles.
     */
    function wpdocs_theme_name_scripts() {
    	wp_enqueue_style( 'style-name', get_stylesheet_uri() );
    	wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
    }
    add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
    

    Never worry about cache again!

    This is a little trick I’ve picked up along the way.
    The version of the .js and .css files is made from the time of it’s last update.

    /**
     * Never worry about cache again!
     */
    function my_load_scripts($hook) {
    
    	// create my own version codes
    	$my_js_ver  = date("ymd-Gis", filemtime( plugin_dir_path( __FILE__ ) . 'js/custom.js' ));
    	$my_css_ver = date("ymd-Gis", filemtime( plugin_dir_path( __FILE__ ) . 'style.css' ));
    	
    	// 
    	wp_enqueue_script( 'custom_js', plugins_url( 'js/custom.js', __FILE__ ), array(), $my_js_ver );
    	wp_register_style( 'my_css', 	plugins_url( 'style.css', 	 __FILE__ ), false,   $my_css_ver );
    	wp_enqueue_style ( 'my_css' );
    
    }
    add_action('wp_enqueue_scripts', 'my_load_scripts');
    

    That way, you will always use the cached versions, except in case the files were changed in the meanwhile, which is the most optimum scenario.

    Link a Theme Script Which Depends on jQuery

    JavaScript files included in themes often require another JavaScript file to be loaded in advance to use its functions or variables. Using the $deps parameter, the wp_enqueue_script() and wp_register_script() functions allows you to mark dependencies when registering a new script. This will cause WordPress to automatically link these dependencies to the HTML page before the new script is linked. If the handles of these dependencies are not registered, WordPress will not link the new script. This example requires the jQuery library for the custom_script.js theme script:

    
    /**
     * Enqueue a script with jQuery as a dependency.
     */
    function wpdocs_scripts_method() {
    	wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom_script.js', array( 'jquery' ) );
    }
    add_action( 'wp_enqueue_scripts', 'wpdocs_scripts_method' );
    

    Link the script.aculo.us Library

    The following is an example of basic usage which links the script.aculo.us library already included and registered by WordPress with the scriptaculous handle.

    
    /**
     * Enqueue script.aculo.us.
     *
     * Tha callback is hooked to 'wp_enqueue_script' to ensure the script is only enqueued on the front-end.
     */
    function my_scripts_method() {
        wp_enqueue_script( 'scriptaculous' );
    }
    add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
    

    The above example links the script.aculo.us library only on the front-end. If the library was needed within the administration screens, you could use the admin_enqueue_scripts action hook instead, however, this would enqueue it on all the administration screens, which often leads to plugin/core conflicts, ultimately breaking the WordPress administration screens experience. Instead, you should only link it on the individual screens you need it, see the Link Scripts Only on a Plugin Administration Screen section for an example of that.

    I want to add a note to bcworkz comment. When using jquery, in general, this is how the code in a file should be formatted:

    
    (function( $ ) {
    
    	"use strict";
    	
    	// javascript code here. i.e.: $(document).ready( function(){} ); 
    
    })(jQuery);
    

    It’s a common practice that ensures jQuery runs in no conflict mode and in strict mode.

    Strict mode helps out in a couple ways:

    • It catches some common coding bloopers, throwing exceptions.
    • It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object).
    • It disables features that are confusing or poorly thought out.

    Because of the work on https://core.trac.wordpress.org/ticket/9346, it’s actually safe to call

    wp_enqueue_script

    after the hook “wp_enqueue_scripts” and before the footer, eg when rendering shortcodes or rendering a post’s body.
    Enqueueing stylesheets (css) in this same method has some issues though.
    Scribu gave an example of a shortcode enqueueing a script here: http://scribu.net/wordpress/conditional-script-loading-revisited.html

    Link a Plugin Script That Depends on script.aculo.us

    This example is intended to be used within a plugin file to register and link a new plugin script that depends on the script.aculo.us library. See the example above for information about dependencies.

    
    /**
     * Enqueue script with script.aculo.us as a dependency.
     */
    function my_scripts_method() {
    	wp_enqueue_script( 'newscript', plugins_url( '/js/newscript.js' , __FILE__ ), array( 'scriptaculous' ) );
    }
    add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
    

    Link Scripts Only on a Plugin Administration Screen

    This example links a script only on a specific administration screen, as opposed to the scenario described in the paragraph below the code of the first example.

    
    <?php
    /**
     * Register the plugin script.
     */
    function wpdocs_plugin_admin_init() {
        // Register our script.
        wp_register_script( 'my-plugin-script', plugins_url( '/script.js', __FILE__ ) );
    }
    add_action( 'admin_init', 'wpdocs_plugin_admin_init' );
    
    /**
     * Add Administration screen for the plugin.
     */
    function wpdocs_plugin_admin_menu() {
        /* Add our plugin submenu and administration screen */
        $page_hook_suffix = add_submenu_page( 'edit.php',	// The parent page of this submenu.
    		__( 'My Plugin', 'my-textdomain' ),				// The submenu title.
    		__( 'My Plugin', 'my-textdomain' ),				// The screen title.
    		'manage_options', 								// The capability required for access to this submenu.
    		'my_plugin-options', 							// The slug to use in the URL of the screen.
    		'wpdocs_plugin_manage_menu' 					// The function to call to display the screen.
    	);
    
        /*
    	 * Use the retrieved $page_hook_suffix to hook the function that links our script.
    	 * This hook invokes the function only on our plugin administration screen,
    	 * see: https://developer.wordpress.org/reference/hooks/admin_print_scripts-hook_suffix/
    	 */
        add_action( "admin_print_scripts-{$page_hook_suffix}", 'wpdocs_plugin_admin_scripts');
    }
    add_action( 'admin_menu', 'wpdocs_plugin_admin_menu' );
    
    /**
     * Enqueue registered script in the admin.
     */
    function wpdocs_plugin_admin_scripts() {
        // Link our already registered script to a page.
        wp_enqueue_script( 'my-plugin-script' );
    }
    
    /**
     * Display callback for the plugin Administration screen.
     */
    function wpdocs_plugin_manage_menu() {
        // Display our administration screen.
    }
    

    This is not documented, but calling this function with $in_footer being `false` actually registers the script in general as a dependency that should be resolved and output, not just for header. Then, when outputting scripts enqueued for the footer, only the scripts that have not been included yet will be output. This leads to behaviour where a script that is enqueued supposedly in the header will appear in the footer if enqueued after the header has already been process. Therefore, $in_footer should actually read and be understood as $in_footer_only.

    This is the place to report it. I’ve updated the table with your changes. Thanks!

    Because this and wp_enqueue_style usesWP_Scripts::enqueue(), which can take an array of handles as it’s first argument, you can also pass an array of handles into wp_enqueue_script/style:

    
    /**
     * Enqueue multiple handles
     */
    function enqueue_multiple() {
        wp_enqueue_script( array( 'backbone', 'jquery', 'iris' ) );
    }
    add_action( 'wp_enqueue_scripts', 'enqueue_multiple' );
    

    See Also:

    wp_enqueue_style

    When registering and enqueueing scripts, you don’t need to call wp_register_script() and wp_enqueue_script(). Just call wp_enqueue_script().
    This:

    
    wp_register_script ( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );
    wp_enqueue_script ( 'custom-script' );
    

    Should simply be:

    
    wp_enqueue_script ( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );
    

    Only register if you don’t know if you’re going to load it immediately.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文