PageSpeed Insights: Preload assets

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
498   0  
·
2021/04/24
·
2 mins read


寫網頁,到後來就會走火入魔,想要跟人比拼速度,當然啦,後面還有一個 Google 大神在鞭策,一天到晚在恐嚇著我們這些可憐寫程式的,說:你的網頁太慢,SEO 就會很爛,哼,我就不相信,如果我的內容是個寶,你敢不連我,可是,我知道,我的內容就不是寶啊,大神啊,請賞口飯吃把。

Google Search Console 內有連到 PageSpeed Insights,大家都在說你的排名跟 PageSpeed Insights 的分數有直接的關係,真相如何,鬼才知道,不過呢,現在比拼 PageSpeed Insights 分數已經是大眾運動了,所以,我也來參與一下,來聊聊:

Preload assets

我覺得 Preload 這個字有點誤導,如果改成像 IMG 的 lazy loading 會更傳神,照慣例,先上碼:

stylesheet_link_tag "style.css"
<link href="/assets/style.css" media="screen" rel="stylesheet" />
<link rel="preload" href="/assets/style.css" as="style">
<link rel="preload" as="style" href="/assets/style.css" onload="this.rel='stylesheet'"/>

<link rel="preload" as="font" type="font/woff2" crossorigin href="//cdn.cdn.com/font.woff2?v=1.2.3"/>
<link rel="preload" href="<%=asset_path("/font.woff2")%>" as="font" type="font/woff2" crossorigin>

<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=google_font&display=swap" rel="stylesheet">

很棒,有行號,那我們就來看看每一行的用途吧:

第 1 跟 2 行:就很標準的 Rails helper 跟用 HTML 把要用的 css 讀進來,很標準,但是保證 PageSpeed Insights 一定直接給你個大建議:請 Preload key requests,「請」是我說的。

第 3 跟 4 行:就是改寫成 preload 後的碼,只是,常常妳改寫成第 3 行後,就會發現 Chrome 的 console 又開始鬼叫:

The resource xyz was preloaded using link preload but not used within a few seconds from the window's load event.
Please make sure it has an appropriate `as` value and it is preloaded intentionally.

哎,嫌你 preload 又不用,確定一下你真的有用到它,真的有,那就改用第 4 行吧,不只 preload 還把它 onload 近來。

第 5 跟 6 行:這是 preload 字型用的,兩者有巨大的差異,第 5 行是 preload CDN 的,第 6 行可是 preload 你的 CSS 內宣告的字型,用 asset_path() 就可以很輕鬆的找到 Rails compiled 的 assets,好用簡單又不黏牙。

第 9 跟 10 行:這沒啥特別,就是用 goole font 的標準寫法,我只是要記錄一下那個有趣的 rel="preconnect" ,這也是 preload 的一種方式, 不要把它刪掉了。

好啦,看是簡單無形,卻可是我一天的心血,老話一句,希望對大家有幫助啦。




WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

This article is part of:
分類於:
標籤:
日期:
創作於:2021/04/24,最後更新於:2021/04/25。
合計:566字


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.