Tag Archives: priority

Chrome 對各種 JavaScript 的優先順序

前陣子看到「JavaScript Loading Priorities in Chrome」這篇,在分析 Google Chrome 對各種 JavaScript 的優先順序。

優先順序分成讀取的「Loading priority (network/Blink)」與執行的「Execution priority」,另外文章裡也有整理建議「Where should this be used?」。

看起來 <script defer> at the end of <body> 是全部裡面最低的,建議是給 Load "Related articles" 或是 "Give feedback" 這類功能,不過應該沒什麼人真的這樣用...

然後要注意的是,這邊分析的對象是 Google Chrome,實際在設計時應該要先考慮一般性的定義,再考慮對各瀏覽器的最佳化... (雖然以現在市占率來說沒什麼人想管其他瀏覽器...)

用 link="preload" 提高下載的優先度

除了讓 browser 自己決定優先權外,在「Preload Scripts」這邊看到的技巧,可以跟 browser 說明哪些資源比較重要,請儘快先下載:

<link rel="preload" href="main.js" as="script">

Link rel=preload is useful for downloading any important resource more quickly, such as stylesheets that contain critical CSS, fonts that are used in important design elements, and hero images. It's especially important for scripts because they block page content from rendering and consume the most CPU during page load.

以作者的想法,這個技巧應該用在會卡住頁面呈現的部分,確保這些資源可以優先下載。

另外作者也提到了可以直接把這個資訊放到 HTTP header 裡面,理論上會更快:

Link: <main.js>; rel="preload"; as="script"

尤其是 sync script 應該會有幫助,建議可以跑 A/B test 看看效果:

We know that synchronous scripts block rendering, which makes the user experience feel slow. And we know that most scripts today are downloaded synchronously (rather than async). And yet only 1% of sites are using link rel=preload to download their scripts. If your site has any synchronous scripts, do an A/B test adding link rel=preload for them. It's likely this will be a win and help you create a more joyous experience for your users.

以 Google Chrome 的情況分析各種 script 的利弊與使用時機

在「Script Scheduling in Chrome」這邊看到關於各種 <script> 的時機,主要是以 Google Chrome 環境為主。作者在文章裡面有提到「Scheduling Scripts Intuitively and Performantly」這份文件,並且將最上面的表格取出來,光是這張表就給了不少想法:

文件裡面有更多細節可以看,而且有些討論其實是在思考要怎麼修改 spec 讓網站更容易設 script priority...