GOV.UK 拔掉網頁上的 jQuery

英國政府的網站拔掉 jQuery 了:「GOV.UK drops jQuery from their front end.」,Hacker News 上的討論也可以看一下:「Gov.uk drops jQuery from their front end (web.dev)」。

當年會選擇用 jQuery 大概有幾個原因,第一個是當年 (很舊的 browser 版本) 對 DOM 的操作非常的混亂,像是:

而 jQuery 在那個年代就已經把這堆 DOM operation 都窮舉支援了 (可以直接看「Category: DOM Insertion, Around」、「Category: DOM Insertion, Inside」、「Category: DOM Insertion, Outside」這三個大分類),可以注意 jQuery 1.0 就已經把基本界面都弄出來了,而 jQuery 1.0 是 2006 年八月出的,另外 IE7 是在 2006 年十月出,也就是說在 IE6 的年代就提供一整套完整的方案。

另外 jQuery 幫忙處理了早期 IE 與 W3C 標準的不一致行為,像是經典的 attachEvent (出自 DOM events):

Microsoft Internet Explorer prior to version 8 does not follow the W3C model, as its own model was created prior to the ratification of the W3C standard. Internet Explorer 9 follows DOM level 3 events, and Internet Explorer 11 deletes its support for Microsoft-specific model.

就功能面上來說,jQuery 提供的 Sizzle engine 也提供了 CSS selector 的能力,這在早期還沒有 querySelectorAll() (IE9+) 的時候方便不少,而且就算有了 querySelectorAll(),Sizzle 支援的 CSS selector 更完整。

上面提到的解決 browser 早期的各種亂象,jQuery 其實也帶入了不少好用的 pattern,其中一個是 fluent interface 讓人寫起來很舒服:(這個範例只是要介紹 fluent interface,不要管實際上在亂搞什麼 XD)

$('#foo').html('<p>bar</p>').css('width: 100px;');

另外就是不需要對 null object 做太多處理:

$('#foo').css('width: 100px;');

與這樣比較:

let elem = document.querySelector('#foo');
if (elem) {
    // ...
}

不過在這些年,負面的部份已經大幅改善了,所以也陸陸續續可以看到很多人在討論要怎麼拔掉 jQuery。而這次英國的 GOV.UK 拔掉 jQuery 有看到一些效果:

  • Less front end processing time overall.
  • 11% less blocking time at the 75th percentile.
  • 10% less blocking time for users at the 95th percentile. These are users who experience seriously adverse network and device conditions, and every performance gain matters especially for them.

但說實話,~10% 左右的 performance 改變比預期中少很多耶?可以看出來 John Resig 當年在上面為了效能花了多少功夫...

這次的結果反倒是讓我在思考,如果可以用 jQuery 降低開發的瓶頸,我還蠻偏好就拿 jQuery 進來用...

One thought on “GOV.UK 拔掉網頁上的 jQuery”

Leave a Reply

Your email address will not be published. Required fields are marked *