注册并排队有条件的(浏览器特定的)javascript文件?


8

该WP.SE社区一直建议使用wp_register_script,并wp_enqueue_script在主题/模板添加脚本(同样地,wp_register_stylewp_enqueue_style为样式表)。


这就是我注册和排队脚本的方式...

首先,我在functions.php中添加类似的内容

add_action('init','wpse54189_register_script');
function wpse54189_register_script(){

    //Register scripts
    wp_enqueue_script( 'jquery' );
    wp_register_script( 'aahan_bootstrap_transition', get_template_directory_uri().'/js/bootstrap-transition.js');
    wp_register_script( 'aahan_bootstrap_carousel', get_template_directory_uri().'/js/bootstrap-carousel.js', array('aahan_bootstrap_transition'));    
    wp_register_script( 'wpse54189_ajax_comment', get_template_directory_uri().'/js/no-reload-comments.js');
}

然后像这样在模板文件(例如header.php)中调用它

<?php wp_enqueue_script( 'aahan_bootstrap_carousel' ); ?>
<?php wp_enqueue_script( 'wpse54189_ajax_comment' ); ?>

现在,至此,我该如何注册和入列特定浏览器可以识别的“条件JavaScript文件”?例如:

<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<![endif]-->

如何正确注册和入队?

PS:我使用Reddle主题,该主题由Automattic的主题牧马人开发。主题的header.php直接使用前面提到的代码-即未排队。那么,这是否意味着这是唯一的方法?


尽管已经快一年了,但之前也问过同样的问题。我之前搜索时没有碰到它。
its_me 2012年

Answers:


13

WP_ScriptsWP_Styles类是落后wp_enqueue_scriptwp_enqueue_style功能。如果您看一下类的实现(脚本样式),那么您会看到WP_Scripts该类不支持任何类型的条件脚本,但是!你会看到的WP_Styles!问题是wp_enqueue_style不允许您设置条件。

因此,我们必须做一个小技巧:

add_filter( 'wp_enqueue_scripts', 'wpse2345_enqueue_scripts' );
function wpse2345_enqueue_scripts() {
    wp_enqueue_style( 'mystyle', 'url/of/my/style.css', array(), '1.0.0' );

    global $wp_styles;
    $wp_styles->registered['mystyle']->add_data( 'conditional', 'lt IE 9' );
}

因为所有注册样式都存储在类的registered字段中,所以这种破解成为可能WP_Styles。每个注册样式都是一个_WP_Dependency类的对象,可让您添加额外的数据。

不幸的是,这种黑客不适用于脚本。

附加信息:
昨晚我实际上正在浏览Aaron Campbell的Essence主题中的代码,并注意到他同时在调用浏览器的条件脚本和样式。

/**
 * @var WP_Scripts
 */
global $wp_scripts;
// Conditionally load this only for IE < 9
$wp_scripts->add_data( 'html5', 'conditional', 'lt IE 9' );

/**
 * @var WP_Styles
 */
global $wp_styles;
// Conditionally load this only for IE < 8
$wp_styles->add_data( 'blueprint-ie', 'conditional', 'lt IE 8' );

也有一个票证和补丁,但还不是核心。显然,没有此补丁,条件脚本将无法工作,但要注意的一件事是,可以直接在附加到wp_enqueue_scripts操作的函数内部使用add_data方法。


1
Unfortunately this hack is not working for scripts.哦,真糟糕!看起来唯一的方法就是它的样子。:(感谢您的入侵。:)
its_me 2012年

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.