jQuery是否会在Wordpress 3.6中自动排队

时间:2013-09-18 14:10:08

标签: jquery wordpress

之前,要在Wordpress中包含jQuery,你必须这样做:

wp_enqueue_script('jquery');

但是,作为确保尚未加载jquery的方法,有些人会这样做:

function sp_load_jquery() {
    // only use this method is we're not in wp-admin
    if ( ! is_admin() ) {
        // deregister the original version of jQuery
        wp_deregister_script('jquery');
        // register it again, this time with no file path
        wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
        // add it back into the queue
        wp_enqueue_script('jquery');
    }
}
add_action('template_redirect', 'sp_load_jquery');

许多人不赞成,他们认为Wordpress在noConflict模式下加载jQuery。

但是,我的终极问题是,似乎在Wordpress 3.6+中jQuery会自动排入Wordpress。有人可以告诉我是否是这种情况吗?

修改

好的,所以在下面的帮助和答案中,这就是我现在所拥有的:

function sp_load_jquery() {
    if ( ! is_admin() && !wp_script_is( 'jquery' ) ) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js", false, null);
        wp_enqueue_script('jquery');
    }
}
add_action('wp_enqueue_scripts', 'sp_load_jquery');

当Wordpress触发wp_enqueue_scripts挂钩时,add_action会加载sp_load_jquery函数。然后该函数检查用户是否没有查看admin(因为jQuery在那里自动加载),并且还检查是否使用Wordpress wp_script_js()函数加载了jQuery。该函数然后使用Wordpress取消注册jQuery,使用Google的CDN重新注册它,然后将Google版本发送回队列。

但是,如果您不想使用Google的CDN,请执行以下操作:

function sp_load_jquery() {
    if ( ! is_admin() && !wp_script_is( 'jquery' ) ) {
        wp_enqueue_script('jquery');
    }
}
add_action('wp_enqueue_scripts', 'sp_load_jquery');

1 个答案:

答案 0 :(得分:3)

您的示例不是为了确保jQuery尚未加载....更多的是保证jQuery的版本已经加载。

如果您正在编写插件,最好尝试编写它,记住wordpress将始终更新到每个版本的jQuery的最新版本(这打破了一些插件)。只需总是将jquery脚本排入队列(无需重新注册),如果它已经入队,那么再次执行它是没有问题的。

编辑:

要查看脚本是否已入队,您可以:

$wpScripts = new WP_Scripts()
if($wpScripts->query('jquery','enqueued')){
    //it is loaded
}

if($wpScripts->query('jquery','registered')){
    //it has been registered
}