近幾年來,JavaScript 可謂風生水起,從後端到前端,從 mobile 到 desktop,各種 module 滿天飛,信手拈來就是一個 web app。不過,「沒碰過 IE,別說你會做前端」,本人從超新手的角度出發,整理最近修正 IE 相容性遇到的坑與解法,給自己日後留個參考。
(撰於 2017-07-15,基於 IE 11/Edge 15)
/** | |
* Calculate the rendered rect of img content (useful with object-fit: contain) | |
* @param {HTMLImageElement} img | |
* @return {object} rect of the object (the coordinate origin is top-left). | |
*/ | |
export function getRenderedRect (img) { | |
const style = window.getComputedStyle(img) | |
const pos = style.getPropertyValue('object-position').split(' ') | |
const contains = style.getPropertyValue('object-fit') === 'contain' |
/** | |
* Get real element offset with an offsetParent referencing element | |
* | |
* `getBoundingClientRect` return values is not correct under CSS multi-column | |
* layout, so we recursively get `offsetLeft`/`offsetTop` instead. | |
* @param {HTMLElement} el - element of interest | |
* @param {HTMLElement} stopEl - one of the offsetParent as a reference | |
* @return {object} object wth top and left offset | |
*/ | |
export function getClientOffset (el, stopEl) { |
/** | |
* GET request with a cancelable token | |
* @param {string} url - url to request | |
* @param {objecg} token - an object with a `cancel` function property. | |
* @return {Promise} | |
*/ | |
export function cancellableGet (url, token) { | |
const xhr = new XMLHttpRequest() | |
return new Promise(function (resolve, reject) { | |
token.cancel = function () { |
在前一篇介紹 [JavaScript Concurrency 的文章][weihanglo-promise]中,Promise 提供開發者安全統一的標準 API,透過 thenable
減少 callback hell,巨幅降低開發非同步程式的門檻,大大提升可維護性。不過,Promise 仍沒達到 JS 社群的目標「Write async code synchronously」。本篇文章將簡單最新的 Concurrency Solution「Async Functions」,利用同步的語法寫非同步的程式,整個人都變潮了呢!
(撰於 2017-06-17,基於 ECMAScript 7+)
const blobURL = URL.createObjectURL(new Blob([ '(', | |
function () { | |
function fibonacci () {} | |
onmessage = function (ev) { | |
const result = processData(ev.data) | |
postMessage(result) | |
} | |
}.toString(), | |
所謂良好的使用者體驗,有個基本要求:「能即時回饋使用者的互動」。在 Mobile Native,常利用多線程(Multi-threading)分散主線程(main thread)的負擔,讓其能即時響應使用者點擊等事件。反觀 web 端的霸主 JavaScript,卻是易被阻塞的單線程(single-threaded)語言,不過藉由 Event Loop 的設計,仍可達成非同步操作,線程不至完全阻塞,或多或少彌補了單線程的不足。
眾所周知,[Concurrency is hard!][concurrency-joke]設計不良的非同步程式,絕對會讓你痛不欲生。本文將簡單介紹 Promise 這個現代 JavaScript Concurrency Features,讓 JS 新標準帶你從地獄回到另一個煉獄人間。
(撰於 2017-06-12,基於 ECMAScript 6+)