jQuery 4.0 改版:捨棄冗餘、擁抱原生 JS 與 ES6 標準

沒有想過隔了這麼多年,jQuery 居然更新了。jQuery 4.0 的發布(這可是睽違近十年的大改版!)標誌著一個時代的轉移。這次更新的核心目標很明確:瘦身與現代化。它拔掉了許多為了相容老舊瀏覽器而存在的冗餘程式碼,並擁抱了現代 JavaScript (ES6+) 的標準。

1. Browser Support

最新版本僅支援 IE 11,過舊的版本就不再支援了。
FeaturejQuery 3.6jQuery 4.0Impact
Internet ExplorerSupports IE 9+DSupports IE 11Code becomes lighter; transpilation might be needed for very old legacy support.
EdgeSupports Edge LegacyDrops Edge LegacyFocus on modern Chromium-Edge.
iOS / MacOSOlder versions supportedDrops iOS < 11, macOS < 10.13Aligns with vendor support cycles.


2. Removed utility methods

jQuery 捨棄既有函數,改採用原生 JavaScript。

Removed MethodNative Replacement (Use this in 4.0)Example Migration
jQuery.trim()String.prototype.trim()$.trim(str) → str.trim()
jQuery.isArray()Array.isArray()$.isArray(arr) → Array.isArray(arr)
jQuery.isFunction()typeof === 'function'$.isFunction(fn) → typeof fn === 'function'
jQuery.isNumeric()typeof check + isNaN$.isNumeric(n) → typeof n === 'number' && !isNaN(n)
jQuery.parseJSON()JSON.parse()$.parseJSON(str) → JSON.parse(str)
jQuery.now()Date.now()$.now() → Date.now()
jQuery.type()typeof / Generics$.type(obj) → typeof obj (logic varies)


3. Event Behavior Changes

事件行為回歸 W3C 標準。
FeaturejQuery 3.6jQuery 4.0
Focus Event OrderCustom order: focusout -> blur -> focusin -> focusW3C Standard: blur -> focusout -> focus -> focusin


4. Internal & Prototype Changes

在 3.x 以前,jQuery 物件雖然不是真正的 Array,但它的 Prototype 裡偷塞了 pushsort 和 splice 這些方法。這讓你有一種錯覺,覺得 jQuery 物件可以直接當陣列來操作。現在這些操作全部改用原生 javascript 方式處理。
FeatureChange
Internal Array Methodspushsortsplice are removed from the jQuery prototype. You can no longer treat a jQuery object exactly like an array for these modifications. Use [].push.call($obj, item) if strictly necessary.
Trusted TypesjQuery 4.0 adds support for Trusted Types, ensuring HTML wrapped in TrustedHTML works safely with manipulation methods.

 

5. Coding Style Recommendation

Legacy Style (jQuery 3.x)

Heavy reliance on jQuery wrappers for everything.

var  arr = [1, 2, 3];

$.each(arr, function(i, val) {

console.log(val);

});

var  json = $.parseJSON('{"a":1}');

Modern Style (jQuery 4.0+)

Use jQuery only for DOM selection/events; use Native JS for logic.

const  arr = [1, 2, 3];

for (const  val  of  arr) {

console.log(val);

}

const  json = JSON.parse('{"a":1}');

Summary

jQuery 4.0 是一次邁向現代化的重大發布。透過移除對過時瀏覽器的支援以及那些早就該淘汰的工具函數,它成功瘦身了約 3KB(經 gzipped 壓縮後)。這次改版的背後邏輯很清楚:它預設你已經在專案中同步使用現代 JavaScript (ES6+) 了。

    Blogger Comment

0 意見: