挖掘https://github.com/WordPress/WordPress/blob/3.5.1/wp-includes/class.wp-dependencies.php 所有注册的脚本都存储在全局$wp_scripts
.
您可以通过它直接访问它们,但我更喜欢在API存在时使用它。在这种情况下,$wp_scripts->query()
返回特定的注册脚本(a_WP_Dependency
对象-see source).
A._WP_Dependency
对象将依赖项存储为句柄数组,您可以直接访问这些句柄并插入依赖项。以下函数用于:
/**
* Add $dep (script handle) to the array of dependencies for $handle
* @see http://wordpress.stackexchange.com/questions/100709/add-a-script-as-a-dependency-to-a-registered-script
* @param string $handle Script handle for which you want to add a dependency
* @param string $dep Script handle - the dependency you wish to add
*/
function wpse100709_append_dependency( $handle, $dep ){
global $wp_scripts;
$script = $wp_scripts->query( $handle, \'registered\' );
if( !$script )
return false;
if( !in_array( $dep, $script->deps ) ){
$script->deps[] = $dep;
}
return true;
}
显然,您必须在原始脚本之间添加此内容(
$handle
) 正在注册并且正在排队。
示例用法script_a
已在上注册init
使用优先级10挂钩,然后您要添加script_b
作为依赖项:
add_action( \'init\', \'wpse100709_register_script_b\', 11 );
function wpse100709_register_script_b(){
//Register script b
wp_register_script( \'script_b\', ... );
//Now add script b as being a pre-requisite for script a
wpse100709_append_dependency( \'script_a\', \'script_b\' )
//If script a is enqueued, script b is enqueued before it.
}