問題描述

我想首先加載頭 j,然後加載所有入隊腳本到它的功能。像這樣…

<script src=">/js/head.load.min.js" type="text/javascript" charset="UTF-8"></script>

<script type="text/javascript">
head.js("/path/to/jquery.js", "/google/analytics.js", "/js/site.js", function() {

   // all done

});
</script>

我該怎麼做?

對於那些不知道 HeadJS 是 2.30KB 的腳本加快,簡化和現代化你的網站…

http://headjs.com/

最佳解決方案

您應該預先警告,並非所有插件/主題都使用排隊。當我第一次開始處理所有的 JavaScripts 和 CSS 文件輸出我剛剛掛鈎入隊列文件。這導致我只得到 10 個 JavaScript 文件中的 2 個和 3 個 CSS 文件中的 1 個。

這是一些快速的 PoC 。沒有測試,但是如果你可以編寫代碼,這意味着讓你走向正確的方向。一旦我回家,我會把一些更加適合和功能的東西打在一起。

add_action('wp_print_scripts','head_files');
function head_files(){

    global $wp_scripts, $auto_compress_scripts;

    print 'print out head.js';

    $queue = $wp_scripts->queue;
        $wp_scripts->all_deps($queue);
        $to_do = $wp_scripts->to_do;
    $headArray = array();
        foreach ($to_do as $key => $handle) {
            $src = $wp_scripts->registered[$handle]->src;
        $headArray[] = $src;
    }

    print 'print out head.js("'.implode("'",$headArray.'")';
}

(基本上從 JS & CSS Script Optimizer 中刷卡大部分代碼)

add_filter('wpsupercache_buffer', 'head_files' );
function head_files($buffer){
    if ( $fileType == "js" ){
            preg_match_all('~<script.*(type="["']text/javascript["'].*)?src=["'](.*)["'].*(type=["']text/javascript["'].*)?></script>~iU',$content,$matches);
            $headArray = $matches[2];
    }


    print 'print out head.js';

    print 'print out head.js("'.implode("'",$headArray.'")';
    return $buffer;
}

使用 WP 超級緩存輸出緩衝。

次佳解決方案

這是我正在努力集成 head.js:

我把這段代碼放在我的模板 functions.php 文件中

define('THEME', get_bloginfo('template_url'), true);
define('THEME_JS', THEME . '/js/', true);

add_action('wp_print_scripts','head_js_files');
function head_js_files()
{
    if (is_admin()) return; //to preserve the admin

        global $wp_scripts;

    $in_queue = $wp_scripts->queue;

    if(!empty($in_queue))
    {
        $scripts = array();
        foreach($in_queue as $script)
        {

            $src = $wp_scripts->registered[$script]->src;
            $src = ( (preg_match('/^(http|https):///', $src)) ? '' : get_bloginfo('url') ) . $src;
            $scripts[] = '{' . $script . ':"' . $src . '"}';
        }

        echo "<script type="text/javascript" src="".THEME_JS."head.js"></script>n";
        echo "<script type="text/javascript">head.js(n". implode(",n", $scripts). "n);</script>n";
    }

    $wp_scripts->queue = array();
}

它輸出這樣的東西:

<script type="text/javascript">head.js(
    {jquery:"/wp-includes/js/jquery/jquery.js"},
    {jquery_lastfm:"http://localhost/lucianomammino/wp-content/plugins/lastfm-recent-tracks-widget/js/jquery.lastfm.js"},
    {nav:"http://localhost/lucianomammino/wp-content/themes/lmtheme/js/jquery.dropdown.js"}
);</script>

請注意,它還使用腳本標籤,有時候可以確定什麼 (以及何時) 腳本加載。

參考文獻

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