問題描述
我有一些 WordPress 域中需要外掛的各種 javascripts,我知道從 php 檔案中呼叫哪裡。
我正在採取一切措施,加快頁面載入時間,網路上的每一個速度測試員都說如果可能的話推遲 javascript 。
我已經閱讀了關於 defer = ‘defer’ 和 javascript 中的非同步函式,我認為其中一個將完成我要完成的任務。但我不明白我如何在 php 檔案中這樣做。
例如,這裡是一個特定外掛的 php 檔案的片段,其中的 javascript 檔案被呼叫:
function add_dcsnt_scripts() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'dcsnt', dc_jqsocialtabs::get_plugin_directory() . '/js/jquery.social.media.tabs.1.7.1.min.js' );
}
我已經閱讀,最好做這樣的事情,以加快頁面載入時間:
<script defer async src="..."></script>
但是我不知道如何在 php 檔案中完成。我想用我所有的 javascript 檔案這樣做。
我如何完成延遲或異動這個 javascript 程式碼片段是最後載入的,並加快頁面載入時間?在所有瀏覽器中增加頁面載入時間的理想方式是什麼?感謝任何人可以提供的任何指導!
最佳解決思路
該 blog post 連結到兩個感興趣的外掛:
Asynchronous Javascript
Improve page load performance by asynchronously loading javascript using head.js
WP Deferred Javascripts
Defer the loading of all javascripts added with wp_enqueue_scripts, using LABJS (an asynchronous javascript library).
沒有測試他們,但檢查程式碼,他們做了漂亮的東西與 WordPress 指令碼入隊過程。
但隨後 WPSE comes to rescue:
// Adapted from https://gist.github.com/toscho/1584783
add_filter( 'clean_url', function( $url )
{
if ( FALSE === strpos( $url, '.js' ) )
{ // not our file
return $url;
}
// Must be a ', not "!
return "$url' defer='defer";
}, 11, 1 );
次佳解決思路
或更普遍的方式:
function add_async_forscript($url)
{
if (strpos($url, '#asyncload')===false)
return $url;
else if (is_admin())
return str_replace('#asyncload', '', $url);
else
return str_replace('#asyncload', '', $url)."' async='async";
}
add_filter('clean_url', 'add_async_forscript', 11, 1);
所以你可以新增非同步到任何指令碼沒有程式碼更改,只需新增 #asyncload 到指令碼 url 為:
wp_enqueue_script('dcsnt', '/js/jquery.social.media.tabs.1.7.1.min.js#asyncload' )
第三種解決思路
另一個解決方案使用不同的過濾器,可以用來定位特定的指令碼控制程式碼:
function frontend_scripts()
{
wp_enqueue_script( 'my-unique-script-handle', 'path/to/my/script.js' );
}
add_action( 'wp_enqueue_scripts', 'frontend_script' );
function make_script_async( $tag, $handle, $src )
{
if ( 'my-unique-script-handle' != $handle ) {
return $tag;
}
return str_replace( '<script', '<script async', $tag );
}
add_filter( 'script_loader_tag', 'make_script_async', 10, 3 );
第四種思路
一種簡化的方法。新增到您的 functions.php 檔案,使 JavaScript 在 Wordpress 非同步
// Make JavaScript Asynchronous in WordPress
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if( is_admin() ) {
return $tag;
}
return str_replace( ' src', ' async src', $tag );
}, 10, 2 );
第五種思路
嘗試使事情有些模組化和全面涵蓋,以下方法動態地選擇如何透過在 $控制程式碼名稱附加一個小識別符號來嵌入標記與非同步或延遲屬性:
/**
* Add async or defer attributes to script enqueues
* @author Mike Kormendy
* @param String $tag The original enqueued <script src="...> tag
* @param String $handle The registered unique name of the script
* @return String $tag The modified <script async|defer src="...> tag
*/
// only on the front-end
if(!is_admin()) {
function add_asyncdefer_attribute($tag, $handle) {
// if the unique handle/name of the registered script has 'async' in it
if (strpos($handle, 'async') !== false) {
// return the tag with the async attribute
return str_replace( '<script ', '<script async ', $tag );
}
// if the unique handle/name of the registered script has 'defer' in it
else if (strpos($handle, 'defer') !== false) {
// return the tag with the defer attribute
return str_replace( '<script ', '<script defer ', $tag );
}
// otherwise skip
else {
return $tag;
}
}
add_filter('script_loader_tag', 'add_asyncdefer_attribute', 10, 2);
}
使用示例
function enqueue_my_scripts() {
// script to load asynchronously
wp_register_script('firstscript-async', '//www.domain.com/somescript.js', '', 2, false);
wp_enqueue_script('firstscript-async');
// script to be deferred
wp_register_script('secondscript-defer', '//www.domain.com/otherscript.js', '', 2, false);
wp_enqueue_script('secondscript-defer');
// standard script embed
wp_register_script('thirdscript', '//www.domain.com/anotherscript.js', '', 2, false);
wp_enqueue_script('thirdscript');
}
add_action('wp_enqueue_scripts', 'enqueue_my_scripts', 9999);
輸出:
<script async type='text/javascript' src='//www.domain.com/somescript.js'></script>
<script defer type='text/javascript' src='//www.domain.com/otherscript.js'></script>
<script type='text/javascript' src='//www.domain.com/anothercript.js'></script>
感謝 @MattKeys @crissoca 在這裡激發我的回答。
第六種思路
為了控制哪些 js 檔案延遲和避免衝突,您可以在 wp_register_script 函式中將變數附加到 url 中,如下所示。
wp_register_script( 'menu', get_template_directory_uri() . '/js/script.js?defer', array('jquery'), '1.0', true );
然後換行:
if ( FALSE === strpos( $url, '.js' ))
至:
if ( FALSE === strpos( $url, '.js?defer' ))
新的過濾器看起來像這樣。
add_filter( 'clean_url', function( $url )
{
if ( FALSE === strpos( $url, '.js?defer' ) )
{ // not our file
return $url;
}
// Must be a ', not "!
return "$url' defer='defer";
}, 11, 1 );
參考文獻
- How do I defer or async this WordPress javascript snippet to load lastly for faster page load times?
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。