Making WordPress.org

Opened 4 years ago

Closed 4 years ago

Last modified 4 years ago

#5200 closed enhancement (invalid)

Update wp_register_script documentation to recommend registration on init instead of wp_enqueue_scripts

Reported by: jhned's profile jhned Owned by:
Milestone: Priority: low
Component: Codex Keywords:
Cc:

Description

I disagree with this part of the documentation for wp_register_script:

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.

Change History (3)

#1 @Otto42
4 years ago

The init action happens before the *_enqueue_scripts hooks, so you will not get a "comprehensive" list at that point in time. Any scripts that are enqueue-ing on the recommended hooks will not be registered or listed at the init hook time.

The reason for waiting until *_enqueue_scripts is that it is the last point in the process when a script can be added before wp_print_scripts outputs them (in the header). Waiting until the last possible moment has the advantage of having everything relevant probably loaded by that point.

#2 @Otto42
4 years ago

  • Resolution set to invalid
  • Status changed from new to closed

Additionally, comments can be left on the documentation there, or brought up to the #docs team directly. Meta trac isn't really the right place for these.

Since you have left a comment on that page already, I'll close this.

#3 @jhned
4 years ago

Thanks for the clarification, I'll continue the discussion with #docs.

Note: See TracTickets for help on using tickets.