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.

1 Answer 1


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.

  • Ah this looks promising! I'll need to refactor it to allow for recursion for the dependencies of dependencies though, give me a few hours to test out
    – Tom J Nowell
    Aug 16, 2020 at 11:41
  • 1
    Sure, take your time. :)
    – Sally CJ
    Aug 17, 2020 at 1:46
  • 1
    I tested this out and produced 2 functions, and can confirm this does what it says on the tin, sorry it took so long but thanks!!!
    – Tom J Nowell
    Sep 21, 2020 at 17:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.