请先检查一下,然后转到wp_Register_script()/wp_enQueue_script

时间:2011-08-22 作者:tsiger

我最近一直在WordPress上玩Modernizer,下面是我正在努力实现的东西。

我在自定义选项页面中添加了一个HTML5输入字段,特别是:

<input type="number" />
现在,使用Modernizr,我可以测试浏览器是否支持以下功能:

Modernizr.load([
{
test: Modernizr.inputtypes.number, // this is the test
nope: [ load js,css etc ] // if it\'s not supported load your custom lib
complete: function() {
  // do something 
}]);
是否可以调用wp\\u register\\u script()/wp\\u enqueue\\u script函数,而不是在“nope”方法中手动加载自定义库?

我的意思是我可以注册/排队我的自定义库,但我只想在必要时这样做(如果浏览器不支持这种类型的输入类型)。

有什么想法吗?

2 个回复
SO网友:bueltge

请检查以下示例Alex Hempton-Smith, 也许这对你有帮助。

<?php

function urls_of_enqueued_scrips( $handles = array() ) {
    global $wp_scripts, $wp_styles;

    foreach ( $wp_scripts->registered as $registered )
        $script_urls[ $registered->handle ] = $registered->src;

    foreach ( $wp_styles->registered as $registered )
        $style_urls[ $registered->handle ] = $registered->src;

    if ( empty( $handles ) ) {

        $handles = array_merge( $wp_scripts->queue, $wp_styles->queue );
        array_values( $handles );

    }

    $output = \'\';

    foreach ( $handles as $handle ) {

        if ( !empty( $script_urls[ $handle ] ) )
            $output .= $script_urls[ $handle ] . \',\';

        if ( !empty( $style_urls[ $handle ] ) )
            $output .= $style_urls[ $handle ] . \',\';

    }

    $output = substr( $output, 0, -1 );

    echo $output;

}

?>

<script>
Modernizr.load([
  {
    test : Modernizr.inputtypes.number,
    nope : [<?php urls_of_enqueued_scrips( array(\'spinbox\') ); ?>],
    complete: function() {
      jQuery(\'.html5-number\').spinbox();
    }
  }
]);
</script>

SO网友:goldenapples

我会这样做(诚然,这并不理想,但我认为这可能是最容易阅读的)。

创建可能需要的所有条件脚本的数组,并使用wp_localize_script (在3.3中,您将能够使用逻辑性更强的别名wp_add_script_datadiscussed here).

$conditional_scripts = array(
    \'spinner\' => get_stylesheet_directory_uri().\'/js/spinbox.js\',
    \'datepicker\' => get_stylesheet_directory_uri().\'/js/datepicker.js\'
    // etc, etc, etc.
);

/* You could tie the variables to anything, since I assume you\'re just using
   an inline script. But including it as a "localization" of modernizr makes
   as much sense as anything. */
wp_localize_script( \'modernizr\', \'modernizrScripts\', $conditional_scripts );
然后只需在Modernizr测试中访问这些变量:

<script>
Modernizr.load([
  {
    test : Modernizr.inputtypes.number,
    nope : modernizrScripts.spinner,
    complete: function() {
      jQuery(\'.html5-number\').spinbox();
    }
  },
  {
    test : Modernizr.inputtypes.date,
    nope : modernizrScripts.datepicker,
    complete: function() {
      jQuery(\'.html5-date\').datepicker();
    }
  }
]);
</script>

结束

相关推荐