沒有想過隔了這麼多年,jQuery 居然更新了。jQuery 4.0 的發布(這可是睽違近十年的大改版!)標誌著一個時代的轉移。這次更新的核心目標很明確:瘦身與現代化。它拔掉了許多為了相容老舊瀏覽器而存在的冗餘程式碼,並擁抱了現代 JavaScript (ES6+) 的標準。
1. Browser Support
最新版本僅支援 IE 11,過舊的版本就不再支援了。
| Feature | jQuery 3.6 | jQuery 4.0 | Impact |
|---|---|---|---|
| Internet Explorer | Supports IE 9+ | DSupports IE 11 | Code becomes lighter; transpilation might be needed for very old legacy support. |
| Edge | Supports Edge Legacy | Drops Edge Legacy | Focus on modern Chromium-Edge. |
| iOS / MacOS | Older versions supported | Drops iOS < 11, macOS < 10.13 | Aligns with vendor support cycles. |
2. Removed utility methods
jQuery 捨棄既有函數,改採用原生 JavaScript。
| Removed Method | Native 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 標準。
| Feature | jQuery 3.6 | jQuery 4.0 |
|---|---|---|
| Focus Event Order | Custom order: focusout -> blur -> focusin -> focus | W3C Standard: blur -> focusout -> focus -> focusin |
4. Internal & Prototype Changes
在 3.x 以前,jQuery 物件雖然不是真正的 Array,但它的 Prototype 裡偷塞了
push、sort 和 splice 這些方法。這讓你有一種錯覺,覺得 jQuery 物件可以直接當陣列來操作。現在這些操作全部改用原生 javascript 方式處理。| Feature | Change |
|---|---|
| Internal Array Methods | push, sort, splice 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 Types | jQuery 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+) 了。
0 意見:
張貼留言