Script dependencies generates different outputs

Question

The block of code below is supposed to generate a list of dependencies for a given handle e.g. jquery.

function get_deps() {
    global $wp_scripts;
    $wp_scripts->all_deps( 'jquery' );
    $output = [];    // Initialize an empty array
    foreach( $wp_scripts->to_do as $handle ) {
        $dep = wp_scripts()->registered[ $handle ];
        $output [] = $dep->src;
    }
    $result = $output;
    return $result;
}

The function below is a quick test of the get_deps function to check if it spits out the expected list of dependencies.

function display_scripts() {
    print_r( get_deps() ) ;
}
add_action( 'wp_enqueue_scripts', 'display_scripts',  PHP_INT_MAX );

This works as expected however if print_r( get_deps() ) ; is called with the script_loader_tag filter, it produces a unexpected list.

As a quick test, if I replace jquery with lazysizes which has no dependencies like so:

function get_deps() {
    global $wp_scripts;
    $wp_scripts->all_deps( 'lazysizes' );
    $output = [];    // Initialize an empty array
    foreach( $wp_scripts->to_do as $handle ) {
        $dep = wp_scripts()->registered[ $handle ];
        $output [] = $dep->src;
    }
    $result = $output;
    return $result;
}

And quickly validate it with:

function display_scripts() {
    print_r( get_deps() ) ;
}
add_action( 'wp_enqueue_scripts', 'display_scripts',  PHP_INT_MAX );

The output is: Array ( ). So far so good. Now if print_r( get_deps() ) ; included in a block of code with the script_loader_tag filter, the results are completely different. Here’s the test:

function test() {
    print_r( get_deps() ) ;
}
add_filter( 'script_loader_tag', 'test', 10 );

which produces:

Array
(
    [0] => /wp-includes/js/jquery/jquery.min.js
    [1] => /wp-includes/js/jquery/jquery-migrate.min.js
    [2] => 
    [3] => https://domain.com/wp-content/themes/theme-name/js/plugins.js
    [4] => https://domain.com/wp-content/themes/theme-name/js/script.js
)
Array
(
    [0] => /wp-includes/js/jquery/jquery-migrate.min.js
    [1] => 
    [2] => https://domain.com/wp-content/themes/theme-name/js/plugins.js
    [3] => https://domain.com/wp-content/themes/theme-name/js/script.js
)

I’ve no idea why it does this since it should be Array(). What am I doing wrong or overlooking?

0
Motivated 2 weeks 2022-09-09T21:44:37-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse