admin管理员组文章数量:1327524
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.
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
Reset to default 2wp_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.
本文标签: Retrieve URL of ScriptStyle and Dependencies
版权声明:本文标题:Retrieve URL of ScriptStyle and Dependencies 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742185287a2429204.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论