In the 8th series of Core Web Vital, let's explain the optimization of JS and CSS.The optimization of distribution (GZIP compression, CDN, browser cache) has already been described in the first "Response to resource distribution", so please refer to that.The following items are optimized this time.
This work is quite troublesome, and tuning is required for each site, so it will be quite broken to introduce it on an existing site with a long history of operation.However, if you do not do this work, you will not be able to eliminate the "reduction of CSS / JavaScript that is not used".
Above all, not to download extra data to users will lead to improved user experiences.
First, let's introduce how to stop reading unnecessary CSS and JS.An asset that is often caught is Contact Form 7 asset.When the recaptcha v3 integration is enabled in Contact Form 7, recaptcha is read on all pages.It is intended for CF7 that is read on all pages, because Google recommends displaying it on multiple pages, but anyway, it is the operation of "turn it off on unused pages".Let's change it.
First of all, most sites are a single page.Of course, you can set up a inquiry form on the sidebar or call toe action, but anyway, it is necessary to judge that this page needs CF7 now.For this reason, let's write a process that determines that "shortcodes and blocks are not necessary if the text is not in the text of the post".
/** * 現在のページがCF7のアセットを必要とするか ** @return bool */function my_cf7_requires_assets() { return is_singular() && has_shortcode( get_queried_object()->post_content, 'contact-form-7' ); }
has_shortcode
は文字列がショートコードを含んでいるかを判定する関数。get_queried_object
は現在のメインクエリに格納されたオブジェクトを返す関数で、シングルページならWP_Post
を返す。要するに、「シングルページかつCF7のショートコードを含んでいたらtrue
」という関数を作ったわけだ。
Let's use this function to stop the asset that is read on all pages.
// WordPressへのJS/CSS登録フックの最後で実行。add_action( 'wp_enqueue_scripts', function() { if ( ! my_cf7_requires_assets() ) {wp_dequeue_style( 'contact-form-7' );wp_dequeue_script( 'contact-form-7' );wp_dequeue_script( 'google-recaptcha' );wp_dequeue_script( 'wpcf7-recaptcha' ); }}, 9999 );
You will not be able to read the CF7 JS/CSS on a page without inquiry form.WP_Dequeue_style is a function that cancels CSS and WP_Dequeue_script is a function that cancels JavaScript.If you don't know the handle name, use the Query Monitor introduced earlier.Let's cut from something that can be asserted that "this is not used", and "absorbed by CSS on the theme side because it is not a big layout".
To improve LCP, you need to complete the main content first.For this purpose, it is better to divide the style of the sidebar and footer and the main content area (mostly header + posted text) CSS to delay CSS with low priority in the former.
If there are multiple layout patterns, for example, if you have one column for fixed pages and 2 columns for this site, the CSS on the fixed page should not include the sidebar.In this case, there are two types of approaches.
With the former pattern, SCSS is as follows.
// page.scss@import "header";@import "content";// single.scss@import "header";@import "content";@import "sidebar";
These are read for each page.
Next, the approach to solve by dependence is as follows.
if ( is_page() ) { wp_enqueue_style( 'my-page', $url, [], $version );} elseif( is_singular() ) { wp_enqueue_style( 'my-single', $url, [ 'my-sidebar' ], $version );} else { wp_enqueue_style( 'my-archives', $url, [], $version ); }
ファイル数が増えるオーバーヘッドとブラウザキャッシュによるメリットを秤にかけると、どちらがいいのかを判断するのは骨が折れるが、いずれにせよひとつのstyle.css
を全ページで読み込むよりは改善されるはずだ。
Core Web Vital's indicator Fib = "First Input Delay" shows the time to interact with users.This is improved by quick rendering in style and JavaScript with a short blocking time.
筆者がよく見かけるパターンとして、スタイルシート同様、すべてのJavaScriptをapp.js
などにバンドルして、あらゆる操作をその中で行う全部乗せのロングタスクだ。Core Web Vitalは一つのJavaScriptに許容されるブロッキングタイムを50m秒と定義し、それを超える時間を合算してTBT(=Total Blocking Time) と位置付けている。ロングタスクはTBTが蓄積しやすい処理だ。たとえば、次のようにjQuery.ready
で何でもかんでも登録するケースである。
jQuery( document ).ready( function() { // スライダーを実行 $( '.sliders' ).slider();</ 開閉パネルを実行 $( '.header-menu' ).each( function( index, menu ) {$( menu ).menu(); } ); // こんな感じであらゆるタスクが登録されている // ....} );
If everything is needed, it can't be helped, but let's not read it on unnecessary pages, dividing it to JavaScript.
By the way, in order to keep a long task, you can use the PERFORMANCE tab of Chrome Dev Tools.Press the recording button to start the performance measurement, and you can check the results after stopping.
All the above graphs with red flags are long tasks.Scroll will zoom in, so you can see which process it takes time.In this way, you can clearly see that the loading of HTML perspective, SDK and advertising tags is all long tasks.
As introduced above, the performance optimization can be measured if you read CSS/JS only when you need it.For example, let's assume the following cases.
こうしたケースでは、すべてのCSSとJSをガッチャンコするのではなく、別々に分割し、存在するものだけ読み込むようにしよう。CF7の例で紹介したように読み込んでもいいが、そもそも register_block_type を使っておけば、使った時だけ読み込まれるようになるWordPress 5.After 8, it will be read only when used.
add_action( 'wp_enqueue_script', function() {
WordPress5 to enable only the necessary blocks.You need to apply a filter hook as of 8 times.
/** * ブロックアセットを分けて読み込み */add_filter( 'should_load_separate_core_block_assets', '__return_true' );
I haven't been able to verify it yet, but for the time being, for the core block, this will be in a state where only the assets used.Giant Block-Library.CSS is not loaded.
Also, if the WordPress version is old or the block asset is loaded in the above code, let's insert the process of "check the post and read the blocks."。It is troublesome to do one by one.
// スクリプト読み込みのときにチェックするadd_action( 'wp_enqueue_scriipt', function() { if ( is_singular() ) {foreach ( $myblocks => $block_name => $handle ) {if ( has_block( $block_name, get_queried_object() ) ) { // シングルページでかつ投稿がブロックを使っている wp_enqueue_style( $handle );}} }} );
It's a little easier to talk in a widget.Better yet, you can read both with the widget output code.
class My_Widget extends WP_Widget {<<<<
wp_head
よりあとにwp_enqueue_*
を呼び出した場合、JSの場合はフッターに、CSSの場合は呼び出した場所に出力される。JSは特に問題ないと思うが、linkタグのスタイルシートは body-ok なのだが、推奨される方法ではないので、こだわりのある方は別の方法を模索してみて欲しい。
In any case, if you divide the file and read it when you need it, you can measure the optimization.
Even if you use a framework like Bootstrap, you often get scolded to "delete CSS that you are not using."This is exactly what you said, so let's use only what you need.First, this is the default Boostrap.
// scss-docs-start import-stack// Configuration@import "functions";@import "variables";@import "mixins";@import "utilities";// Layout & components@import "root";@import "reboot";@import "type";@import "images";@import "containers";@import "grid";@import "tables";@import "forms";@import "buttons";@import "transitions";@import "dropdown";@import "button-group";@import "nav";@import "navbar";@import "card";@import "accordion";@import "breadcrumb";@import "pagination";@import "badge";@import "alert";@import "progress";@import "list-group";@import "close";@import "toasts";@import "modal";@import "tooltip";@import "popover";@import "carousel";@import "spinners";@import "offcanvas";// Helpers@import "helpers";// Utilities@import "utilities/api";// scss-docs-end import-stack
First, the following "Configuration" is a file defined by mixin, functions, variables, etc., and Bootstrap cannot be compiled unless it is read.
@import "functions";@import "variables";@import "mixins";@import "utilities";
Next is "Components", but these are each part.The following are those that are likely to be used on any page.
@import "root";@import "reboot";@import "type";@import "images";@import "containers";@import "grid";
The rest will be set to be read as necessary, and it will be exported as a separate CSS ... but here one serious problem will come up.
In the first place, among users who use CSS frameworks such as Bootstrap, it is rare for those who use this way.I use a framework because I want to make it easier, and it is not easy to consider the contents carefully.This can be said to be the same, not limited to Bootstrap, but using any CSS framework.
Of course, Bootstrap has room to reduce the theme (color type, Primary or Success), and remember that it is not so easy."If you didn't use the CSS framework, you wouldn't have been able to release the first time," he said, and I want you to survive this painful time.
さらなる最適化Tipsとして「小さいCSS・JSをインライン展開せよ」というTipsがある。WordPressのようなCMSでは、同じ雛形から複数のコンテンツが作られるので、インライン展開はしなくてもよいというのが筆者の持論だ。複数のページをユーザーが見た場合、インライン展開だと同じコード断片(タグの中身)を毎回ダウンロードする羽目になるが、外部スタイルシートならばブラウザキャッシュが効く。
Of course, this is a matter of considering the entire site in total, so this does not apply if you absolutely expand inline.Plugins such as autooptimize support CSS inline distribution.
The content introduced this time included a lot of code correction.The ways are different for each site, and it will be a painful task.I don't want to repeat what I have experienced here again, so I want you to accumulate good knowledge by saying, "I'm told that the PSI score is low after delivery anyway, so let's do it from the beginning."
Navigation Lists
Stop loading unnecessary JS/CSS CSS divides the main content and others Divide JS processing Read JS/CSS only when needed Only what you need if you use a framework Should I deploy inline? summaryCategory
Related Articles
Hot Articles