問題描述

我有一些 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 );

參考文獻

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