[WordPress] 外掛分享: Inline JavaScript in Head

首頁外掛目錄 › Inline JavaScript in Head
10+
安裝啟用
☆☆☆☆
1/5 分(1 則評價)
2149 天前
最後更新
問題解決
WordPress 4.0+ PHP 5.4+ v1.2.0 上架:2019-03-10

內容簡介

注意:這個外掛現在已經被棄用!它的後繼外掛是Embed JavaScript File Content。新的外掛程序是從頭開始重新構建的,更加穩定可靠:它尊重腳本的順序和位置,而且通過wp_add_inline_script或wp_localize_script添加的額外腳本不會丟失。請試用一下它!

在某些情況下,即使JavaScript文件被放在模板的<head>部分的早期位置,您也不能等待其加載。如果將JavaScript代碼直接放在<script>標籤中,放在標題中,可以使性能更好。這就是這個外掛的用途:它提供了一個inline_javascript_in_head_handles過濾器,該過濾器接受JavaScript handles,取消列隊這些腳本,並將它們的代碼內容直接嵌入到標題中,而不是通過腳本標籤連接它們。

請注意,在<head>部分放置大量的JavaScript代碼可能是危險的!首先,您將失去緩存的好處,其次,文檔大小容易增加。一般的經驗法則是,只有當JavaScript文件是關鍵的,並且文件大小低於 500 字節左右時,才應考慮將其放在標題的內嵌位置。

示例
add_action( 'wp_enqueue_scripts', 'my_scripts' );
function my_scripts() {
// 一些關鍵性腳本正在列隊
wp_enqueue_script( 'js-detection', get_template_directory_uri() . '/js/js-detection.js' );
}

/**
* 定義要在 HTML 標題部分內嵌的 JavaScript handles。
*/
add_filter( 'inline_javascript_in_head_handles', 'my_inline_javascript_in_head_handles', -20 );
function my_inline_javascript_in_head_handles( $handles ) {
$scripts = [ 'js-detection' ];

return array_merge( $handles, $scripts );
}

外掛標籤

開發者團隊

⬇ 下載最新版 (v1.2.0) 或搜尋安裝

① 下載 ZIP → 後台「外掛 › 安裝外掛 › 上傳外掛」
② 後台搜尋「Inline JavaScript in Head」→ 直接安裝(推薦)
📦 歷史版本下載

原文外掛簡介

CAUTION: This plugin is now deprecated! The successor plugin is Embed JavaScript File Content. The new plugin is rebuild from scratch and more rock solid: It respects order and position of scripts and extra scripts added via wp_add_inline_script or wp_localize_script don’t get lost. Give it a try!
In some cases you cannot wait for a JavaScript file to load, even if it is placed early in the section of your template. You can benefit from better performance, if you place the JavaScript code directly inside a

文章
Filter
Mastodon