Make WordPress Core

Opened 7 years ago

Last modified 17 months ago

#41990 new defect (bug)

wp_add_inline_script() does not print if the handler has already processed

Reported by: satollo's profile satollo Owned by:
Milestone: Future Release Priority: normal
Severity: normal Version: 4.5
Component: Script Loader Keywords: has-patch 2nd-opinion needs-testing
Focuses: Cc:

Description

If the wp_add_inline_script() function (with 'after' position set) is called after the head scripts have already been printed and the handler specified on wp_add_inline_script() is part of the head printed scripts, the code is not added later in the footer.

Probably it should. Example a plugin which implements a shortcode needs to add some jquery inline statement only when the shortcode is executed (to add the js code only on relevant pages). It enqueues jquery to be added in the footer and a piece of inline script.

But another plugin or the theme enqueues jquery in the header (as many do): the above inline code is not printed but it actually does not need to be exactly after the jquery inclusion.

Stefano.

Attachments (1)

41990.diff (1.2 KB) - added by Howdy_McGee 17 months ago.

Download all attachments as: .zip

Change History (5)

#1 @swissspidy
7 years ago

  • Component changed from General to Script Loader

#2 @ocean90
6 years ago

#44709 was marked as a duplicate.

#3 @ocean90
6 years ago

  • Keywords needs-patch added
  • Milestone changed from Awaiting Review to Future Release
  • Version changed from 4.8.1 to 4.5

@Howdy_McGee
17 months ago

#4 @Howdy_McGee
17 months ago

  • Keywords has-patch 2nd-opinion needs-testing added; needs-patch removed

I agree that it makes sense to run the 'after' script extras in the footer if they're missed during the wp_head runtime. The provided patch modifies WP_Scripts::add_inline_script() and checks if wp_print_scripts has run. If so, the handle is added to a new WP_Scripts::deferred_extras property which is looped through during WP_Scripts::do_footer_items(). Using wp_print_scripts ensures this functions on both the front-end and admin.

One issue I found while testing this patch is it's all-or-nothing. The WP_Scripts Class does not keep track of which extras have been printed. Calling wp_add_inline_script() for the same $handle in wp_enqueue_scripts and then a 2nd time in a future hook such as wp_body_open (for example) results in all 'after' extras being printed to the footer. Should we keep track of which extras have been printed?

This feature needs more discussion. This patch needs more testing and more feedback.

Note: See TracTickets for help on using tickets.