web-dev-qa-db-ja.com

Modernizrが最初にチェックし、それからwp_register_script()/ wp_enqueue_scriptに進む。

私は最近WordPressでModernizrで遊んでいますが、ここで私が達成しようとしていることがあります。

カスタムオプションページに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 
}]);

自分のカスタムライブラリを "nope"メソッドに手動でロードする代わりに、wp_register_script()/ wp_enqueue_script関数を呼び出すことは可能でしょうか。

私は自分のカスタムライブラリを登録/キューに入れることができるということですが、それが必要な場合にのみ行いたいのです(ブラウザがこの種の入力タイプをネイティブサポートしていない場合)。

何か案は?

1
tsiger

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>
2
bueltge

私はこのようにしてそれをするでしょう(確かに、それは理想的ではありません、しかし私はそれがおそらく最も読みやすいと思います)。

必要なすべての条件付きスクリプトの配列を作成し、wp_localize_scriptを使用してそれらをjavascriptに渡します(3.3以降は、ここで説明する のように、はるかに論理的な別名wp_add_script_dataを使用できます )。

$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>
2
goldenapples