homeappliancesbrands
  • Home
  • blog
  • privacy policy
  • about us
  • English
    • English
    • Japanese
  • Home
  • /
  • Article
  • /
  • [WV.8] Optimize WordPress...

[WV.8] Optimize WordPress JS and CSS


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.

  1. 不要な読み込みをなくす(特にプラグイン)
  2. CSS・JS自体を分割し、必要な時だけ読み込む。

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.

Stop loading unnecessary JS/CSS

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".

CSS divides the main content and others

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.

  1. SASSなどを利用し、別々のCSSを用意する
  2. コンポーネントごとのCSSを用意し、依存関係で解決する。

With the former pattern, SCSS is as follows.

【WV.8】WordPressのJSおよびCSSを最適化する

// 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 を全ページで読み込むよりは改善されるはずだ。

Divide JS processing

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.

Read JS/CSS only when needed

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.

Only what you need if you use a framework

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.

Should I deploy inline?

さらなる最適化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.

summary

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."


12 / Sep / 2022 homeappliancesbrands

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? summary

Category

blog

Related Articles

10.Apr.2023

From prosthetic leg maker to shoe salesperson Using medical knowledge to extend healthy life expectancy from feet Keio Department Store Naoko Ogawa

It used to be said that people lived to be 60 years old, but now we are entering an era of 100 years. Looking around the city, the number of energetic seniors has increased. However, it seems that the strength of the legs and lower back is directly linked to life expectancy as one ages. Not limited to the elderly, it is a little difficult to walk...

09.Apr.2023

Keisuke Higashi, Sakura Fujiwara, Tokihide Wakabayashi, Airu Kubozuka, and Riko appear in "Fight Song" starring Kaya Kiyohara

(Clockwise from top left) Keisuke Higashi, Sakura Fujiwara, Riko, Airu Kubozuka, Tokihide Wakabayashi (c) TBS In the January 2022 TBS Tuesday drama "Fight Song", Keisuke Higashi, Sakura Fujiwara, Toki Wakabayashi It has been decided that Ei, Airu Kubozuka, and Riko will appear. 【photograph】...

08.Apr.2023

A roundup of gadgets and apps that make working from home (remote work) more efficient

If it looks good, even better. Since working from home has become the norm, don't you feel like there are more moments when you need new items? It is very popular in the United States because it thoroughly compares various gadgets and proposes recommendations.

07.Apr.2023

Released a vertically wide WUXGA resolution 24.1-inch monitor that can be easily connected to a notebook PC with a single USB Type-C cable

EIZO Corporation (Headquarters: Hakusan City, Ishikawa Prefecture, President: Yoshitaka Sanemori) will release the 24.1-inch WUXGA LCD monitor "FlexScan EV2485" on September 28th. The price is an open price*. * Standard prices are not set for open price products. ...

Hot Articles

EVsmart blog Toyota's electric car "bZ4X" that makes you feel comfortable with electric cars and quick chargers / No% display of battery level [Editorial department] Popular articles Recent posts Category

EVsmart blog Toyota's electric car "bZ4X" that makes you feel comfortable with electric cars and quick chargers / No% display of battery level [Editorial department] Popular articles Recent posts Category

23.Apr.2022
 Lenovo's 8.8 inch one-handed tab "Legion Y700" full specs released!  [Is the price in the 40,000 yen range?]

Lenovo's 8.8 inch one-handed tab "Legion Y700" full specs released! [Is the price in the 40,000 yen range?]

01.May.2022
# Remote desktop from the beginning-Connecting to your home computer from outside (IPv4)

# Remote desktop from the beginning-Connecting to your home computer from outside (IPv4)

28.Apr.2022
What is the mechanism of "universal control" that enables direct cooperation just by arranging Mac and iPad side by side?

What is the mechanism of "universal control" that enables direct cooperation just by arranging Mac and iPad side by side?

30.Mar.2022

Tags

How to change which monitor is primary

Copyright © 2023 homeappliancesbrands.com. All rights reserved.