問題描述
WP 有一個很好的 javascript 加載器包含在 wp-admin 中:http://core.trac.wordpress.org/browser/tags/3.0.4/wp-admin/load-scripts.php
和一個 CSS 加載器:http://core.trac.wordpress.org/browser/tags/3.0.4/wp-admin/load-styles.php
我想知道是否可以在 front-end 中使用它們,而不僅僅是管理員,因為它們可以連接所有入隊腳本,並將它們作為單個 gzip 壓縮文件
最佳解決方案
遲到的答案
簡要介紹一下:
你必須使用
-
include( admin_url().'load-scripts.php' ); -
和
include( admin_url().'script-loader.php' );
然後跳入 $GLOBALS['wp_scripts']:
使用…
$wp_scripts->default_dirs( array_merge(
$wp_scripts->default_dirs
,array( '/themes/your_theme/js/' )
);
… 擴展它
然後使用
$wp_scripts->add( $handle, $path_from_content_dir, false/array( $deps ), $ver )
添加腳本。
筆記:
-
未壓縮腳本由
.dev.js(SCRIPT_DEBUG為TRUE) 進行搜索。 -
$wp_styles似乎也是可以的。 -
編輯:當 (
SCRIPT_DEBUG為TRUE) 時,WP 3.5 將更改此行為並使用.js作為”dev” 版本和”.min.js”;
(但是我猜這隻有使用插件或 mu-plugin 才有效。)
沒有測試,如果這樣工作,我不知道。
次佳解決方案
這是一個非常好的問題,將是 WordPress 包含的一個很好的功能。
其他一些答案沒有解決主要問題。
I was wondering if it’s possible to use them in the front-end too, not just admin, because they can concatenate all enqueued scripts, and serve them as a single gzipped file.
目前不可能使用內置的腳本加載器來連接前端的 css 和腳本。
幾年前有一個 discussion about this on WP Hackers,有一個 trac ticket for this enhancement 被接受,但是將來的版本。
第三種解決方案
如果您需要在前端排列一個 CSS 文件:
1) 通過 wp_register_style($ handle,$ src) 註冊樣式 2) 將鈎子 wp_enqueue_style($ handle) 插入到 wp_print_styles 鈎子中。
如果您需要在前端排列一個腳本:
1) 通過 wp_register_script($ handle,$ src) 註冊樣式 2) 將鈎子 wp_enqueue_script($ handle) 插入到 wp_head 鈎子中。
(注意:我會預期這個 wp_print_styles 鈎子,但這個鈎子顯然不按預期工作。)
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。