Question

Given script X Y and Z how would I get the list in PHP of X Y Z and their dependencies?

I need to load several scripts that have dependencies.

Normally I would do this via wp_enqueue_script but in this situation I need to load these scripts in a shadow DOM for a webcomponent, and cannot rely on wp_head and wp_footer, I have to construct the DOM elements myself in JS. This is so that the contents of the component are isolated from the rest of the page for styling purposes.

Was it helpful?

Solution

wp_enqueue_script() and wp_enqueue_style() both use WP_Dependencies::add() which initializes a new instance of _WP_Dependency (see wp_scripts() and wp_styles()), so all the script's dependencies are stored in the deps property of the class instance.

However, that property only stores the handle names of the script's dependencies, e.g. jquery-migrate and jquery-core for the default/core jQuery script (handle name: jquery), so to get the actual URL of a dependency file (script/stylesheet), we would need to use WP_Dependencies::all_deps() and then loop through WP_Dependencies::$to_do to get the dependency's src value:

// Enqueue a script:
wp_enqueue_script( 'my-script', '/path/to/file.js', [ 'jquery' ] );

// Get all its dependencies:
wp_scripts()->all_deps( 'my-script' );
foreach ( wp_scripts()->to_do as $handle ) {
    $dep = wp_scripts()->registered[ $handle ];
    var_dump( $dep->handle, $dep->src );
    // or do something with $dep->src ...
}

// Enqueue a style:
wp_enqueue_style( 'my-style', '/path/to/file.css', [ 'foo-dep' ] );

// Get all its dependencies:
wp_styles()->all_deps( 'my-style' );
foreach ( wp_styles()->to_do as $handle ) {
    $dep = wp_styles()->registered[ $handle ];
    var_dump( $dep->handle, $dep->src );
    // or do something with $dep->src ...
}

Note that the $dep->src can be a false if the dependency contains a dependency, e.g. the default jquery handle which has jquery-migrate as a dependency. (But don't worry, the dependencies will be in the to_do array.) And secondly, the to_do array also includes the actual file, e.g. file.js in the above example.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top