問題描述

所以我正在使用 Starkers 來基於我的下一個 WP 主題,我遇到了一個小問題,我在 header.php 文件中包含了我自己的 jQuery 版本,但是當我使用 Firebug 檢查我的網站時,我注意到 jquery 被下載了兩次,我做了一些挖掘,注意到不僅包括文件,而且是 wp_head()功能。

在嘗試解決這個問題時,我注意到頭文件中的一個註釋,其中源自二十十個主題:

/* Always have wp_head() just before the closing </head>
 * tag of your theme, or you will break many plugins, which
 * generally use this hook to add elements to <head>, such 
 * as styles, scripts, and meta tags
 */

所以這裏是我的問題,我的印象是,jQuery 文件必須在任何其他要使用它的文件之前設置,而 wp_head()應該是<head> 元素中的最後一件事,現在我稍微感到困惑想知道我應該把 wp_head()放在頂部,所以 WP 包含的 jQuery 文件將被用於所有的插件,即使它不這樣做。

我在 wp_head()功能中註釋了 jQuery 行,但是管理頁面是必需的,所以我不得不把它放回來。

我還想使用 (至少實驗) 使用 Google CDN 版本的 jQuery,但不想包含它兩次!

我希望你明白我正在解釋什麼,關於我如何解決這個問題的任何建議將是最值得讚賞的。我也會感謝任何關於如何使用頭文件處理 JavaScript 文件的建議。

謝謝!

最佳解決方案

從您的問題的措辭,您必須通過在模板中編寫<script> 標籤來添加腳本。通過 wp_enqueue_script()在模板的 functions.php 中添加自己的腳本,適當地設置對 jQuery 的依賴性,wp_head()將為您添加腳本。

function my_scripts() {
    wp_enqueue_script( 'my-sweet-script', get_bloginfo('template_directory') . '/script.js', array('jquery') );
}
add_action('template_redirect', 'my_scripts');

有關更多信息,請參閲 codex page

次佳解決方案

我建議看看 5 Tips for using jQuery with WordPress 。除此之外,它顯示了從 Google 的庫加載 jQuery 所需的代碼:

function my_init() {
    if (!is_admin()) {
        // comment out the next two lines to load the local copy of jQuery
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://googleajax.admincdn.com/ajax/libs/jquery/1.3.2/jquery.min.js', false, '1.3.2');
        wp_enqueue_script('jquery');
    }
}
add_action('init', 'my_init');

您也可以查看 Use Google Libraries 插件。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。