內容簡介
在一些關鍵的情況下,你無法等待 JavaScript 檔案載入。這時如果直接將 JavaScript 代碼嵌入到 <script> 標籤中,你可以獲得更好的效能。這就是這個外掛程式的用途:它提供了一個過濾器 embed_javascript_file_content_handles,可以接受 JavaScript handle,將其代碼內容直接輸出到 DOM 中,而不是連結到檔案。
請注意,嵌入大量的 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' );
}
/**
* 定義需要內聯儲存的 JavaScript handle,以在 html head 節點中輸出它們的內容。
*/
add_filter( 'embed_javascript_file_content_handles', 'my_embed_javascript_file_content_handles' );
function my_embed_javascript_file_content_handles( $handles ) {
$scripts = [ 'js-detection' ];
return array_merge( $handles, $scripts );
}
外掛標籤
開發者團隊
📦 歷史版本下載
原文外掛簡介
In some critical cases you cannot wait for a JavaScript file to load. Then you can benefit from better performance, if you embed the JavaScript code directly into the
