wp_prototype_before_jquery()
云策文档标注
概述
wp_prototype_before_jquery() 函数用于重新排序 JavaScript 脚本数组,确保 prototype 在 jQuery 之前加载,以避免依赖冲突。
关键要点
- 函数接收一个字符串数组参数 $js_array,表示 JavaScript 脚本数组。
- 通过 array_search 查找 prototype 和 jQuery 在数组中的位置,如果任一不存在则返回原数组。
- 如果 prototype 的位置在 jQuery 之后,则交换两者顺序,确保 prototype 优先加载。
- 函数返回重新排序后的数组,仅在需要时进行修改。
代码示例
function wp_prototype_before_jquery( $js_array ) {
$prototype = array_search( 'prototype', $js_array, true );
if ( false === $prototype ) {
return $js_array;
}
$jquery = array_search( 'jquery', $js_array, true );
if ( false === $jquery ) {
return $js_array;
}
if ( $prototype < $jquery ) {
return $js_array;
}
unset( $js_array[$prototype] );
array_splice( $js_array, $jquery, 0, 'prototype' );
return $js_array;
}注意事项
- 此函数自 WordPress 2.3.1 版本引入,用于处理脚本依赖顺序问题。
- 仅当 prototype 和 jQuery 同时存在于数组中且 prototype 在 jQuery 之后时才进行重排序。
- 使用严格模式(true 参数)进行 array_search,确保精确匹配脚本名称。
原文内容
Reorders JavaScript scripts array to place prototype before jQuery.
Parameters
$js_arraystring[]required-
JavaScript scripts array
Source
function wp_prototype_before_jquery( $js_array ) {
$prototype = array_search( 'prototype', $js_array, true );
if ( false === $prototype ) {
return $js_array;
}
$jquery = array_search( 'jquery', $js_array, true );
if ( false === $jquery ) {
return $js_array;
}
if ( $prototype < $jquery ) {
return $js_array;
}
unset( $js_array[ $prototype ] );
array_splice( $js_array, $jquery, 0, 'prototype' );
return $js_array;
}
Changelog
| Version | Description |
|---|---|
| 2.3.1 | Introduced. |