Make WordPress Core


Ignore:
Timestamp:
12/07/2021 05:44:46 PM (3 years ago)
Author:
audrasjb
Message:

Script Loader: Allow for wp_register_script() to be called after wp_enqueue_script().

When a plugin registers styles/scripts on wp_enqueue_scripts (as plugin authors are encouraged to do), and conditionally enqueues their script/style on the_content filter, things "just work". In block themes, the_content is run prior to the header being processed, which results in the above scenario failing.

This change makes a wp_enqueue_script( 'example' ); wp_register_script( 'example' ); work, where as currently the enqueue silently fails (no "doing it wrong" message) and the following register has no impact. Scripts can therefore be enqueued and dequeued (by "handle") before they are registered.

Fixes #54529.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/class.wp-dependencies.php

    r51851 r52338  
    9494     */
    9595    private $all_queued_deps;
     96
     97    /**
     98     * List of assets enqueued before details were registered.
     99     *
     100     * @since 5.9.0
     101     *
     102     * @var array
     103     */
     104    private $queued_before_register = array();
    96105
    97106    /**
     
    249258        }
    250259        $this->registered[ $handle ] = new _WP_Dependency( $handle, $src, $deps, $ver, $args );
     260
     261        // If the item was enqueued before the details were registered, enqueue it now.
     262        if ( array_key_exists( $handle, $this->queued_before_register ) ) {
     263            if ( ! is_null( $this->queued_before_register[ $handle ] ) ) {
     264                $this->enqueue( $handle . '?' . $this->queued_before_register[ $handle ] );
     265            } else {
     266                $this->enqueue( $handle );
     267            }
     268
     269            unset( $this->queued_before_register[ $handle ] );
     270        }
     271
    251272        return true;
    252273    }
     
    335356                    $this->args[ $handle[0] ] = $handle[1];
    336357                }
     358            } else if ( ! isset( $this->registered[ $handle[0] ] ) ) {
     359                $this->queued_before_register[ $handle[0] ] = null; // $args
     360
     361                if ( isset( $handle[1] ) ) {
     362                    $this->queued_before_register[ $handle[0] ] = $handle[1];
     363                }
    337364            }
    338365        }
     
    361388                unset( $this->queue[ $key ] );
    362389                unset( $this->args[ $handle[0] ] );
     390            } else if ( array_key_exists( $handle[0], $this->queued_before_register ) ) {
     391                unset( $this->queued_before_register[ $handle[0] ] );
    363392            }
    364393        }
Note: See TracChangeset for help on using the changeset viewer.